zoukankan      html  css  js  c++  java
  • Asp.net网站使用HttpHandler实现图片防盗链功能

    第一步:创建PicHandler.cs文件,代码如下:

    using System.Web;

    namespace MyHttpModule
    {
        public class PicHandler:IHttpHandler
        {
            public void ProcessRequest(HttpContext context)
            {
                string strFile = context.Server.MapPath(context.Request.FilePath);
                if(context.Request.UrlReferrer==null)
                {
                    context.Response.ContentType = "image/JPEG";
                    context.Response.WriteFile("/error.jpg");
                }
                else
                {
                    if(context.Request.UrlReferrer.Host.IndexOf("youdomain.com")>-1)
                    {
                        context.Response.ContentType = "imae/jpeg";
                        context.Response.WriteFile(strFile);
                    }
                    else
                    {
                        context.Response.ContentType = "image/JPEG";
                        context.Response.WriteFile("/error.jpg");
                    }
                }
            }

            /// <summary>
            
    /// 获取一个值,该值指示其他请求是否可以使用IHttpHander实例。也就是后续的Http请求是不是可以继续使用实现了该接口的类的实例
            
    /// </summary>
            public bool IsReusable
            {
                get { return true; }
            }
        }
    }

    第二步:编译文件成DLL;

     csc /t:library /r:System.Web.dll PicHandler.cs

    第三步:将编译妇的DLL拷贝到Bin目录下;

    第四步:在Web.config中注册这个Handler;

    <httpHandlers>
      <add path="*.jpg" verb="*" type="MyHttpHandler.PicHandler,MyHttpHandler"/>
    </httpHandlers>

    第五步:在IIS中配置应用程序扩展(jpg)

    C:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll

  • 相关阅读:
    模板方法模式
    抽象工厂模式
    工厂方法模式
    简单工厂模式
    策略模式
    原型模式
    单例模式
    遍历一个二维数组的简便方法(减少foreach次数)
    数组最后一个元素的 引用在 foreach 循环之后仍会保留。建议使用 unset() 来将其销毁
    PHP 中for循环的一个小小改进
  • 原文地址:https://www.cnblogs.com/AngelLee2009/p/2228250.html
Copyright © 2011-2022 走看看