使用HttpHandler对象实现防盗链
文章目录
前言
一些不良网站为了在不增加成本的前提下扩充自己站点内容,经常盗用其他网站的资源(如图片)这种现象称为盗链。盗链一方面损害了原网站的合法利益,另一方面也加重了服务器的负担。
一、什么是HttpHandler?
IHttpHandler定义了如果要实现一个HTTP请求的处理所必需实现的一些系统约定。HttpHandler与HttpModule不同,一旦定义了自己的HttpHandler类,那么它对系统的HttpHandler的关系将是“覆盖”关系。
二、使用步骤
1.创建一个网站
页面引用图片并能正常显示
<div>
<img src="Img/59254fb7e7bce71354b2c669.jpg" width="256px" height="160px"/>
<img src="Img/5992d1642549594919aa837c.jpg" width="256px" height="160px"/>
<img src="Img/59eadeafe7bce77a990cea6f.jpg" width="256px" height="160px"/>
</div>
2.创建第二个网站
再创建一个新的项目,在这个项目网站上引用第一个的网站上的jpg图片
<div>
<p>第二个网站</p>
<img src="http://localhost:49334/Img/59254fb7e7bce71354b2c669.jpg" width="256px" height="160px"/>
<img src="http://localhost:49334/Img/5992d1642549594919aa837c.jpg" width="256px" height="160px"/>
<img src="http://localhost:49334/Img/59eadeafe7bce77a990cea6f.jpg" width="256px" height="160px"/>
</div>
打开第一个项目网站,右键复制图像链接即可
3.创建HttpHandler类
public class PreventLink : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
Uri lastUrl = context.Request.UrlReferrer;
Uri currentUrl = context.Request.Url;
if (lastUrl.Host!=currentUrl.Host||lastUrl.Port!=currentUrl.Port)
{
string errorlmagePath = context.Request.PhysicalApplicationPath + "Error/defaulu.jpg";
context.Response.WriteFile(errorlmagePath);
}
else
{
context.Response.WriteFile(context.Request.PhysicalPath);
}
}
}
4.在Web.config中
<system.codedom>
<handlers>
<add verb="*" path="Img/*.jpg" name="handlers" type="WebApplication8.HttpHandler"></add>
</handlers>
</system.codedom>
总结
就这么简单,有手就行