C#图片防盗链
1 写一个继承自IHttpHandler的类,并生成DLL;
using System;
using System.Web;
using System.Collections.Generic;
using System.Text;
namespace ImgProtect
{
public class ImgProtectHadler:IHttpHandler
{
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
string path = context.Request.PhysicalPath;
string serverHost = context.Request.Url.Host;
Uri u = context.Request.UrlReferrer;
if (u == null || u.Host.ToLower() != serverHost.ToLower())
{
context.Response.WriteFile("~/Forbidden.gif");
}
else
{
context.Response.WriteFile(path);
}
}
}
}
2 在网站中引用 该DLL;
3 在Web.config中加入
<httpHandlers>
<add verb="*" path="*.jpg,*.jpeg,*.gif,*.png,*.bmp" type="ImgProtect.ImgProtectHadler"/>
</httpHandlers>