当前位置: 移动技术网 > IT编程>开发语言>.net > Asp.net 图片文件防盗链(尊重劳动成果)及BeginRequest事件学习

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

2017年12月12日  | 移动技术网IT编程  | 我要评论
关于图片盗链这个问题,毕竟是自己的劳动成功,很多人不希望别人就那么轻易地偷走了。 这个功能在很多的论坛上都具有,可能是因为盗链的行为太多了吧 反盗链的程序其实很简单,熟悉a
关于图片盗链这个问题,毕竟是自己的劳动成功,很多人不希望别人就那么轻易地偷走了。 这个功能在很多的论坛上都具有,可能是因为盗链的行为太多了吧

反盗链的程序其实很简单,熟悉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();
}
}

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网