ASP.net 使用HttpHandler实现图片防盗链
首先是HttpHandler类的代码:
using System;
using System.Collections.Generic;
using System.Web;
namespace HttpHandler
{
public class JPEGHandler : IHttpHandler
{
#region IHttpHandler 成员
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
string fileName = context.Request.FilePath;
if (context.Request.UrlReferrer.Host == null)
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/no.jpg");
}
else
{
if (context.Request.UrlReferrer.Host.IndexOf("localhost") >= 0)
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(fileName);
}
else
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/no.jpg");
}
}
}
#endregion
}
}
然后是web.config中的代码:
<configuration> <system.web> <httpHandlers> <add verb="*" path="*.jpg" type="HttpHandler.JPEGHandler"/> </httpHandlers> </configuration>
最后就是在网站根目录下放入no.jpg就可以了。
浙公网安备 33010602011771号