C# 圖片防盜鏈怎麼做
使用httpHandle來實現,對圖片文件的請求做專門的處理
第一步:創建一個類,繼承自IHttpHandler,代碼如下
C# codeusing 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中不包含自己站點主機域名,則顯示一張默認的禁止盜鏈的圖片
//string serverHost = context.Request.Url.Host;
//Uri u = context.Request.UrlReferrer;
//if (u == null || u.Host.ToLower() != serverHost.ToLower())
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; }
}
}
}
第二步:編譯成DLL
csc /t:library CustomHandler.cs
第三步:添加編譯好的DLL引用到當前站點的bin文件夾下
第四步:在Web.Config 中註冊這個Handler
C# code<system.web>
<httpHandlers>
<add path="*.jpg,*.jpeg,*.gif,*.png,*.bmp" verb="*" type="CustomHandler.JpgHandler,CustomHandler" />
</httpHandlers>
</system.web>
//verb指的是請求此文件的方式,可以是post或get,用*代表所有訪問方式。CustomHandler.JpgHandler表示命名空間和類名,CustomHandler表示程序集名。
-----------------
IHttpHandler的妙用(1):給圖片添加水印
http://blog.csdn.net/zhoufoxcn/archive/2008/01/10/2033530.aspx
==============
在IIS 對ISAPI進行設置。讓圖片文件.jpg等和isapi.dll關聯起來
如何在IIS中設置ISAPI來進行文件與處理程序映射:
- 打開IIS,選擇本範例所用的站點,右鍵,選擇“屬性”。
- 選擇“主目錄”選項卡,點擊“配置...”按鈕。
- 點擊“添加”,設置“可執行文件”爲“C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/aspnet_isapi.dll”,設置“擴展名”爲“.rss”,點“確定”。
- 注意,不要勾選“檢查文件是否存在”複選框,這樣不用創建文件,只要在地址欄輸入任意以.rss後綴結尾的文件名,均會交由上面創建的Handler去處理,而不管這個文件是否存在,也不管請求的是Article.rss還是Sample.rss。