ASP.NET 实现简单的图片防盗链介绍
在此,网站图片防盗链的方法是,通过获取Http请求头中的 Referer 标头与本网站域名比较,来判断用户是否来自本站跳转过来的 。
创建一个全局处理程序,用来处理images目录下的图片的直接请求:
using System;
using System.Web;
/// <summary>
///DaoLian 的摘要说明
/// </summary>
public class DaoLian:IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
//
//当前请求 的地址
Uri url = context.Request.Url;
Uri urlReferrer = context.Request.UrlReferrer;
if (urlReferrer != null)
{
//判断域名和端口号是否相等
if (IsSameDomain(url,urlReferrer))
{
//获取当前请求的图片的绝对路径
string path = context.Request.MapPath(context.Request.RawUrl);
context.Response.WriteFile(path);
}
else
{
//盗链图片的地址
string path = context.Request.MapPath("../daolian.jpg");
context.Response.WriteFile(path);
}
}
else
{
//盗链图片的地址
string path = context.Request.MapPath("../daolian.jpg");
context.Response.WriteFile(path);
}
}
//判断域名和端口号是否相等
bool IsSameDomain(Uri url1,Uri url2)
{
return Uri.Compare(url1, url2, UriComponents.HostAndPort, UriFormat.Unescaped, StringComparison.CurrentCultureIgnoreCase) == 0;
}
}
using System.Web;
/// <summary>
///DaoLian 的摘要说明
/// </summary>
public class DaoLian:IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
//
//当前请求 的地址
Uri url = context.Request.Url;
Uri urlReferrer = context.Request.UrlReferrer;
if (urlReferrer != null)
{
//判断域名和端口号是否相等
if (IsSameDomain(url,urlReferrer))
{
//获取当前请求的图片的绝对路径
string path = context.Request.MapPath(context.Request.RawUrl);
context.Response.WriteFile(path);
}
else
{
//盗链图片的地址
string path = context.Request.MapPath("../daolian.jpg");
context.Response.WriteFile(path);
}
}
else
{
//盗链图片的地址
string path = context.Request.MapPath("../daolian.jpg");
context.Response.WriteFile(path);
}
}
//判断域名和端口号是否相等
bool IsSameDomain(Uri url1,Uri url2)
{
return Uri.Compare(url1, url2, UriComponents.HostAndPort, UriFormat.Unescaped, StringComparison.CurrentCultureIgnoreCase) == 0;
}
}