ASP.NET 实现防盗链

2023-06-08,,

using System;

using System.Web;

namespace CustomHandler{

public class JpgHandler : IHttpHandler{

public void Proce***equest(HttpContext context){

// 获取文件服务器端物理路径

string FileName = context.Server.MapPath(context.Request.FilePath);

// 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片

if (context.Request.UrlReferrer.Host == null){

context.Response.ContentType = "p_w_picpath/JPEG";

context.Response.WriteFile("/error.jpg");

}else{

// 如果 UrlReferrer中不包含自己站点主机域名,则显示一张默认的禁止盗链的图片

if (context.Request.UrlReferrer.Host.IndexOf("yourdomain.com") > 0){

context.Response.ContentType = "p_w_picpath/JPEG";

context.Response.WriteFile(FileName);

}else{

context.Response.ContentType = "p_w_picpath/JPEG";

context.Response.WriteFile("/error.jpg");

}

}

}

public bool IsReusable{

get{ return true; }

}

}

}

<system.web>

<httpHandlers>

<add path="*.jpg,*.jpeg,*.gif,*.png,*.bmp" verb="*" type="CustomHandler.JpgHandler,CustomHandler" />

</httpHandlers>

</system.web>

//verb指的是请求此文件的方式,可以是post或get,用*代表所有访问方式。CustomHandler.JpgHandler表示命名空间和类名,CustomHandler表示程序集名。

《ASP.NET 实现防盗链.doc》

下载本文的Word格式文档,以方便收藏与打印。