首页 > 代码库 > .net使用httpHandler添加图片防盗链

.net使用httpHandler添加图片防盗链

.net使用httpHandler添加图片防盗链
1. 配置web.config:

  <!--图片添加水印的配置-->                <httpHandlers>                        <add verb="*" path="*.jpg" type="LinkHandler" />                </httpHandlers>  <!--图片添加水印的配置结束-->

2. OutLinkHandler.cs:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Drawing;using System.IO;/// <summary>///HttpHandler 实现防盗链效果/// </summary>public class LinkHandler:IHttpHandler{    public LinkHandler() { }            //1. 设置不能允许重用            public bool IsReusable            {                get { return false; }            }            //2. 编写最终处理程序            public void ProcessRequest(HttpContext context)            {                //context.Request.UrlReferrer.Host   //主机名                //context.Request.Url.Port  //端口号 <wbr>  <wbr>  <wbr>  <wbr>  <wbr>  <wbr>  <wbr>  <wbr> //context.Request.UrlReferrer.Authority   <wbr>//服务器端IP                //根据Ip地址和端口号判断                if (context.Request.UrlReferrer.Authority == "192.168.123.184" &&                context.Request.UrlReferrer.Port == context.Request.Url.Port)                    {                            context.Response.ContentType="image/jpeg";                            context.Response.WriteFile(context.Request.PhysicalPath);                    }                else                    {                    context.Response.ContentType="image/jpeg";                    context.Response.WriteFile(context.Request.PhysicalApplicationPath+"images/1/LinkError.jpg");                    }            }}

 

.net使用httpHandler添加图片防盗链