ASP.NET全局文件與防盜鏈
阿新 • • 發佈:2017-05-11
system 處理程序 處理 tle 盜鏈 title fly bject script
添加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記錄到日誌中。
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的處理程序),一次只能添加一個擴展名
還有一種更簡便的方法就是在Web.config 裏面設置 在 <system.webServer> 節點裏面添加如下:
<!-- 設置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. 自定義的 HttpHandler
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時和上面一樣
ASP.NET全局文件與防盜鏈