ASP.NET全局文件与防盗链

添加Web→全局应用程序类,注 文件名不要改 Global.asax
全局文件是对Web应用声明周期的一个事件响应的地方,将Web应用启动时初始化的一些代码写到
Application_Start中,好比后面讲的Log4Net的初始化等。应用关闭的时候Application_End调用
当一个Session启动的时候Session_Start被调用,Session结 (用户主动退出或者超时结 )
Session_End被调用。当一个用户请求来的时候Application_BeginRequest方法被调用当应用中出
现未捕获异常,Application_Error被调用(常考,ASP.Net中的错误处理机制),
用HttpContext.Current.Server.GetLastError()得到异常信息,而后用 Log4Net记录到日志中。 web

 

1.经过全局配制实现图片的防盗链

 

//jztu.jpg 禁止盗链的图片
protected void Application_BeginRequest(object sender,EventArgs e)
{
    if (HttpContext.Current.Request.Url.AbsolutePath.EndsWith(".jpg")&&
        HttpContext.Current.Request.UrlReferrer.Host != "www.gao.com")
    {    
        HttpContext.Current.Response.WriteFile(HttpContext.Current.
        Server.MapPath("~/jztu.jpg"));
        HttpContex.Current.Response.End();
    }else{
        // 验证经过输出用户请求的文件
        HttpContext.Current.Response.TransmitFile(HttpContext.Current.Request.PhysicalPath);
    }
}

 

屏蔽指定的IP地址

 

protected void Application_BeginRequest(object sender,EventArgs e)
{
    if (HttpContext.Current.Request.UserHostAddress == "127.0.0.1")
    {    
        HttpContext.Current.Response.Write("该IP以被屏蔽!");
        HttpContext.Current.Response.End();
    }else{
        // 验证经过输出用户请求的文件
        HttpContext.Current.Response.TransmitFile(HttpContext.Current.Request.PhysicalPath);
    }
}

IIS发布注意事项:发布到IIS上须要设置一下IIS的 处理程序映射->添加脚本映射->请求路径(*.jpg)->可执行文件(ASP.NET的处理程序),一次只能添加一个扩展名api

还有一种更简便的方法就是在Web.config 里面设置 在 <system.webServer> 节点里面添加以下:ui

<!-- 设置IIS对指定扩展的处理程序为ASP.NET -->
<handlers>
    <add name="防盗链 png" path="*.png" verb="*" modules="IsapiModule" scriptProcessor="%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" preCondition="classicMode,runtimeVersionv4.0,bitness32" />
</handlers>

 

经过自定义 HttpHandler 实现盗链

 1. 自定义的 HttpHandlerspa

public class Protect : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
           if (HttpContext.Current.Request.Url.AbsolutePath.EndsWith(".jpg")&&
        HttpContext.Current.Request.UrlReferrer.Host != "www.gao.com")
       {    
        HttpContext.Current.Response.WriteFile(HttpContext.Current.
        Server.MapPath("~/jztu.jpg"));
        HttpContex.Current.Response.End();
        }else{
            // 验证经过输出用户请求的文件
            HttpContext.Current.Response.TransmitFile(HttpContext.Current.Request.PhysicalPath);
        }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

2. 在Web.config还要在 <system.web> 下配置模块日志

      <!-- 指定某些扩展名的程序给指定的程序解析,可指定多个 -->
      <httpHandlers>
        <add verb="*" path="*.png,*.jpg,*.gif,*.png,*.mp3,*.wma,*.lrc" type="FlyMusic.Web.Com.Protect,FlyMusic.Web"/>
      </httpHandlers>

3. 发布到IIS时和上面同样code

相关文章
相关标签/搜索