.net学习图片防盗链
代码实现如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
///全局处理程序
///1、新建类,实现IHttpHandler
///2、实现相应的功能
///3、配置web.config
<httpHandlers>
<!-- type="命名空间.类名,程序集的名字"-->
<add verb="*"《请求类型 get post》 path="img/*.jpg" 《那个路径下的图片》 type="DaoLian"《类名》/>
</httpHandlers>
/// </summary>
public class DaoLian:IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
//当前请求
Uri u1 = context.Request.Url;
//上一次请求
Uri u2 = context.Request.UrlReferrer;
//比较域名和端口是否一致
if (CompareUrl(u1, u2))
{
//正常的请求
string path = context.Request.RawUrl;
path = context.Request.MapPath(path);
context.Response.WriteFile(path);
}
else
{
//盗链的请求
//相对路径 相对于浏览器当前请求的文件
string path = context.Request.MapPath("daolian.jpg");
context.Response.WriteFile(path);
}
}
//比较两个uri的域名和端口是否相等
bool CompareUrl(Uri u1, Uri u2)
{
return Uri.Compare(u1, u2, UriComponents.HostAndPort, UriFormat.SafeUnescaped, StringComparison.CurrentCultureIgnoreCase) == 0;
}
}