本文通过HttpHandler实现ASP.NET图片防盗技术,非设定网站域名请求图片,输出指定错误图片替换原链接图片。
具体步骤:
一、在Web.config中注册HttpHandler
<httpHandlers> <!--映射jpg格式的文件,给ProcessHandler_test.CustomHandler处理。--> <!--type里面逗号之前 命名空间加类名(ProcessHandler_test.CustomHandler),后面程序集名称--> <add path="*.jpg" verb="*" type="httphander_test.CustomHandler, ProcessHandler_test" /> </httpHandlers>
上面注册是把网站中请求jpg格式文件的请求,映射给命名空间为httphander_test类名为CustomHandler的程序集ProcessHandler_test来处理请求。
二、如果想通过HttpHandler处理请求,需要在映射的处理程序中实现接口IHttpHandler
三、映射到的程序代码如下
namespace httphander_test { public class CustomHandler :IHttpHandler { public void ProcessRequest(HttpContext context) { // 获取文件服务器端物理路径 string FileName = context.Server.MapPath(context.Request.FilePath); // 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片 if (context.Request.UrlReferrer.Host == null) { context.Response.ContentType = "image/gif"; context.Response.WriteFile("/error.gif"); } else { // 如果 UrlReferrer中不包含自己站点主机域名,则显示一张默认的禁止盗链的图片 if (context.Request.UrlReferrer.Host.IndexOf("pcitk.com") > 0) { context.Response.ContentType = "image/gif"; context.Response.WriteFile(FileName); } else { context.Response.ContentType = "image/gif"; context.Response.WriteFile("/error.gif"); } } } public bool IsReusable { get { throw new NotImplementedException(); } } } }
共有条评论 网友评论