使用HttpHandler实现图片防盗链
NOTE:這個(gè)例子來(lái)自于《Maximizing ASP.NET Real World, Object-Oriented Development》一書(shū):
Step.1:創(chuàng)建文件 CustomHandler.cs,代碼如下:
using System;
using System.Web;
namespace CustomHandler{
??? public class JpgHandler : IHttpHandler{
?????? public void ProcessRequest(HttpContext context){
?????????? // 獲取文件服務(wù)器端物理路徑
?????????? string FileName = context.Server.MapPath(context.Request.FilePath);
?????????? // 如果UrlReferrer為空,則顯示一張默認(rèn)的禁止盜鏈的圖片
?????????? if (context.Request.UrlReferrer.Host == null){
????????????? context.Response.ContentType = "image/JPEG";
????????????? context.Response.WriteFile("/error.jpg");
?????????? }else{
????????????? // 如果 UrlReferrer中不包含自己站點(diǎn)主機(jī)域名,則顯示一張默認(rèn)的禁止盜鏈的圖片
???????????? 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 編譯這個(gè)文件
csc /t:library /r:System.Web.dll CustomHandler.cs
Step.3 將編譯好的 CustomHandler.dll 拷貝到站點(diǎn)的 Bin 目錄下。
Step.4 在Web.Config 中注冊(cè)這個(gè)Handler。
<system.web>
??? <httpHandlers>
????? <add path="*.jpg" verb="*" type="CustomHandler.JpgHandler, CustomHandler" />
??? </httpHandlers>
</system.web>
轉(zhuǎn)載于:https://www.cnblogs.com/top5/archive/2009/11/09/1598869.html
總結(jié)
以上是生活随笔為你收集整理的使用HttpHandler实现图片防盗链的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 导出到Excel的操作
- 下一篇: 使用Aspose.Cells的基础知识整