asp.net中利用ashx实现图片防盗链

1 using System;
 2 using System.Collections;
 3 using System.Data;
 4 using System.Web;
 5 using System.Web.Services;
 6 using System.Web.Services.Protocols;
 7 
 8 
 9 namespace GetImage
10 {
11     /// <summary> 
12     /// $codebehindclassname$ 的摘要说明
13     /// </summary> 
14     [WebService(Namespace = "http://tempuri.org/")]
15     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
16     public class Img : IHttpHandler
17     {
18         public void ProcessRequest(HttpContext context)
19         {
20             context.Response.ContentType = "image/jpg";
21             if (context.Request.UrlReferrer != null && context.Request.UrlReferrer.Host.Equals(context.Request.Url.Host, StringComparison.InvariantCultureIgnoreCase))
22             {
23                 context.Response.WriteFile(context.Server.MapPath("~/" + context.Request.QueryString["img"]));
24             }
25             else
26             {
27                 context.Response.WriteFile(context.Server.MapPath("~/logo.gif"));
28             }
29                 
30 
31         }
32 
33         public bool IsReusable
34         {
35             get
36             {
37                 return false;
38             }
39         }
40     }
41 }

 

 

 表示如果来源不为空,并且来源的服务器和当前服务器一致,那就表示是正常访问,非盗链。正常访问文件内容。

否则就是盗链,返回网站LOGO。

你甚至可以做成随机返回正确的图片,随机返回错误图片,或者定时返回正确图片,定时返回错误图片。

然后就是图片的使用了,这时使用图片就不是直接<input type="image" src="111_work.gif" />了,而是<input type="image" src="/Img.ashx?img=111_work.gif" />,就是说通过img,ashx来读取图片。别人盗链的话要用下面代码:<input type="image" src="http://www.123.cn/Img.ashx?img=111_work.gif" />。

赶紧给自己的网站加上防盗链吧!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值