關于圖片盜鏈這個問題,畢竟是自己的勞動成功,很多人不希望別人就那么輕易地偷走了。 這個功能在很多的論壇上都具有,可能是因為盜鏈的行為太多了吧
反盜鏈的程序其實很簡單,熟悉asp.net 應用程序生命周期的話很容易就可以寫一個,運用httpmodule在beginrequest事件中攔截請求就ok了,剩下的工作就是過濾,再過濾!
如果不熟悉httpmodule的話,可以去msdn上查閱,介紹非常詳細,地址:ms-help://ms.vscc.v80/ms.msdn.v80/ms.visualstudio.v80.chs/dv_aspnetcon/html/f1d2910f-61d0-4541-8af8-c3c108ca351f.htm。這里就不廢話了
1private void application_beginrequest(object source, eventargs e)
2{
3 httpapplication application = (httpapplication)source;
4 httpcontext context = application.context;
5 bool issafe = true; //是否合法鏈接
6 string uri = context.request.url.absolutepath.tolower();
7 if (uri.lastindexof(".") > 0 && context.request.urlreferrer != null)
8 {
9 string exp = uri.substring(uri.lastindexof("."));
10 //這里是判斷文件后綴名是否在排除的文件類型列表之內
11 bool ishas = classlibrary.rdata.rstring.strisincusesc(exp, config.imgsafetype.split('|'));
12 if (ishas)
13 {
14 string domainoutter = context.request.urlreferrer.authority.tolower(); //包含域名和端口
15 arraylist arry = common.cache.getdomainvalid();//取系統定義的合法的域名綁定列表
16 issafe = arry.contains(domainoutter); //判斷當前請求的域名是否在合法列表之內
17 }
18 }
19 //下面就是不合法的時候的輸出了,如果有默認替代圖片則輸出,如果沒有就生成一個,格式為.gif
20 if (!issafe)
21 {
22 bitmap img = null;
23 graphics g = null;
24 memorystream ms = null;
25
26 try
27 {
28 string picpath = classlibrary.rpath.getfulldirectory("images/unlawful.gif");
29 if (file.exists(picpath))
30 {
31 img = new bitmap(picpath, false);
32 }
33 else
34 {
35 img = new bitmap(64, 64);
36 g = graphics.fromimage(img);
37 g.clear(color.white);
38 font f = new font("宋體,黑體,arial", 9,fontstyle.bold);
39 solidbrush s = new solidbrush(color.red);
40 g.drawstring(resources.message.lawlesslink, f, s, 1, 20);
41 img.save(picpath, imageformat.gif);
42 }
43 ms = new memorystream();
44 img.save(ms, imageformat.gif);
45 context.response.clearcontent();
46 context.response.contenttype = "image/gif";
47 context.response.binarywrite(ms.toarray());
48 context.response.end();
49 }
50 catch
51 { }
52 finally
53 {
54 if(g != null )
55 g.dispose();
56 img.dispose();
57 }
58 }
59}
凡是有利必有害,這樣做最大的缺點就是增加了系統開銷,客戶端的每一請求都要過濾一遍,性能自然要打折扣了。不知道哪位朋友有更好的辦法,或者優化的方法,一起來探討探討。
新聞熱點
疑難解答