Asp.net 图片文件防盗链(尊重劳动成果)及BeginRequest事件学习

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Asp.net 图片文件防盗链(尊重劳动成果)及BeginRequest事件学习脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
关于图片盗链这个问题,毕竟是自己的劳动成功,很多人不希望别人就那么轻易地偷走了。 这个功能在很多的论坛上都具有,可能是因为盗链的行为太多了吧

反盗链的程序其实很简单,熟悉ASP.NET 应用程序生命周期的话很容易就可以写一个,运用HttpModule在BeginRequest事件中拦截请求就ok了,剩下的工作就是过滤,再过滤!

如果不熟悉HttpModule的话,可以去MSDN上查阅,介绍非常详细,地址:ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_aspnetcon/htML/F1d2910f-61d0-4541-8af8-c3c108ca351f.htm.这里就不废话了
复制代码 代码如下:

PRivate void Application_BeginRequest(Object source, Eventargs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
bool isSafe = true; //是否合法链接
string uri = context.Request.Url.AbsolutePath.ToLower();
if (uri.LastIndexOf(“.”) > 0 && context.Request.UrlReferrer != null)
{
string exp = uri.Substring(uri.LastIndexOf(“.”));
//这里是判断文件后缀名是否在排除的文件类型列表之内
bool isHas = ClassLibrary.RData.RString.StrIsIncUseSC(exp, config.imgSafeTyPE.SplIT(‘|'));
if (isHas)
{
string domainOutter = context.Request.UrlReferrer.Authority.ToLower(); //包含域名和端口
ArrayList arry = Common.Cache.GetDomainValid();//取系统定义的合法的域名绑定列表
isSafe = arry.Contains(domainOutter); //判断当前请求的域名是否在合法列表之内
}
}
//下面就是不合法的时候的输出了,如果有默认替代图片则输出,如果没有就生成一个,格式为。gif
if (!isSafe)
{
Bitmap img = null;
Graphics g = null;
MemoryStream ms = null;

try
{
string picPath = ClassLibrary.RPath.GetFullDirectory(“images/unlawful.gif”);
if (File.Exists(picPath))
{
img = new Bitmap(picPath, false);
}
else
{
img = new Bitmap(**, **);
g = Graphics.FromImage(img);
g.Clear(Color.White);
Font f = new Font(“宋体,黑体,Arial”, 9,FontStyle.Bold);
SolidBrush s = new SolidBrush(Color.red);
g.DrawString(Resources.Message.LawlessLink, f, s, 1, 20);
img.Save(picPath, ImageFormat.Gif);
}
ms = new MemoryStream();
img.Save(ms, ImageFormat.Gif);
context.Response.ClearContent();
context.Response.ContentType = “image/Gif”;
context.Response.BinaryWrite(ms.ToArray());
context.Response.End();
}
catch
{ }
finally
{
if(g != null )
g.Dispose();
img.Dispose();
}
}
}

凡是有利必有害,这样做最大的缺点就是增加了系统开销,客户端的每一请求都要过滤一遍,性能自然要打折扣了。不知道哪位朋友有更好的办法,或者优化的方法,一起来探讨探讨

实现文件放盗链的功能再续
首先添加一个全局文件 Global.aSAX
在 Application_BeginRequest中我们可以判断Http报文头中的UrlReferre是否来本站。
复制代码 代码如下:

if (HttpContext.current.Request.UrlReferrer != null)
{
if (HttpContext.Current.Request.Url.AbsolutePath.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) && HttpContext.Current.Request.UrlReferrer.Host != "localhost")
{
HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("~/jzdl.jpg"));
HttpContext.Current.Response.End();
}
}

脚本宝典总结

以上是脚本宝典为你收集整理的Asp.net 图片文件防盗链(尊重劳动成果)及BeginRequest事件学习全部内容,希望文章能够帮你解决Asp.net 图片文件防盗链(尊重劳动成果)及BeginRequest事件学习所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: