源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

asp.net HttpHandler实现图片防盗链

  • 时间:2020-07-11 02:11 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:asp.net HttpHandler实现图片防盗链
Step.1:创建文件 CustomHandler.cs,代码如下:
[u]复制代码[/u] 代码如下:
using System; using System.Web; namespace CustomHandler{ public class JpgHandler : IHttpHandler{ public void ProcessRequest(HttpContext context){ // 获取文件服务器端物理路径 string FileName = context.Server.MapPath(context.Request.FilePath); // 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片 if (context.Request.UrlReferrer.Host == null){ context.Response.ContentType = "image/JPEG"; context.Response.WriteFile("/error.jpg"); }else{ // 如果 UrlReferrer中不包含自己站点主机域名,则显示一张默认的禁止盗链的图片 if (context.Request.UrlReferrer.Host.IndexOf("yourdomain.com") > 0){ context.Response.ContentType = "image/JPEG"; context.Response.WriteFile(FileName); }else{ context.Response.ContentType = "image/JPEG"; context.Response.WriteFile("/error.jpg"); } } } public bool IsReusable{ get{ return true; } } } }
Step.2 编译这个文件
[u]复制代码[/u] 代码如下:
csc /t:library /r:System.Web.dll CustomHandler.cs
Step.3 将编译好的 CustomHandler.dll 拷贝到站点的 Bin 目录下。 Step.4 在Web.Config 中注册这个Handler。
[u]复制代码[/u] 代码如下:
<system.web> <httpHandlers> <add path="*.jpg" verb="*" type="CustomHandler.JpgHandler, CustomHandler" /> </httpHandlers> </system.web>
OK,诸位可以按步骤自行测试一下,这里就不赘述了。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部