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" />。
赶紧给自己的网站加上防盗链吧!