【概述】html
URL重寫就是首先得到一個進入的URL請求而後把它從新寫成網站能夠處理的另外一個URL的過程。重寫URL是很是有用的一個功能,由於它可讓你提升搜索引擎閱讀和索引你的網站的能力;並且在你改變了本身的網站結構後,無須要求用戶修改他們的書籤,無需其餘網站修改它們的友情連接;它還能夠提升你的網站的安全性;並且一般會讓你的網站更加便於使用和更專業。web
【過程】瀏覽器
實現安全
一、新建一個 【ASP.NET 空Web應用程序】項目:WebApp,並添加一個1.html的文件app
二、 在解決方案中先添加一個【類庫】項目:UrlReWriter,在項目中添加類:MyHttpModule,該類繼承IHttpModule接口,代碼以下:測試
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Text.RegularExpressions; 6 using System.Web; 7 8 namespace UrlReWriter 9 { 10 public class MyHttpModule : IHttpModule 11 { 12 public void Init(HttpApplication context) 13 { 14 context.BeginRequest += new EventHandler(ContextOnBeginRequest); 15 } 16 17 private void ContextOnBeginRequest(object sender, EventArgs eventArgs) 18 { 19 HttpApplication application = sender as HttpApplication; 20 HttpContext context = application.Context; 21 string url = context.Request.Url.LocalPath; 22 23 Regex reg = new Regex(@"(.*)?\.haha$"); 24 if (reg.IsMatch(url)) 25 { 26 context.RewritePath(reg.Replace(url,"$1.html")); 27 } 28 } 29 30 public void Dispose() 31 { 32 throw new NotImplementedException(); 33 } 34 } 35 36 }
能夠看出此類的做用是將後綴爲.haha的請求路徑重寫爲.html網站
三、在WebApp項目中添加UrlReWriter項目的引用,並在WebApp項目中的Web.config文件中添加以下配置(紅色部分爲添加的)搜索引擎
<?xml version="1.0" encoding="utf-8"?> <!-- 有關如何配置 ASP.NET 應用程序的詳細信息,請訪問 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules> <add name="UrlReWriter" type="UrlReWriter.MyHttpModule,UrlReWriter"/> </modules> </system.webServer> </configuration>
關於配置文件的說明:url
IIS應用程序池有兩種模式,一種是「集成模式」,一種是「經典模式」。spa
在 經典模式 下,配置文件須要將httpModules節點添加到system.web節點中,而在集成模式下,須要將httpModules節點改成modules節點,並放到system.webServer節點中。
即:再經典模式下的配置文件應該這樣寫(紅色部分爲添加):
<?xml version="1.0" encoding="utf-8"?> <!-- 有關如何配置 ASP.NET 應用程序的詳細信息,請訪問 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> <httpModules> <add name="UrlReWriter" type="UrlReWriter.MyHttpModule,UrlReWriter"></add> </httpModules> </system.web> </configuration>
若是是集成方式,請用第一種配置文件
四、測試
再瀏覽器中輸入地址http://localhost:31872/1.haha
由於在管道中攔截了這次請求,並將地址重寫爲http://localhost:31872/1.html,因此最終會將1.html頁面返回給瀏覽器。
原文連接:https://www.cnblogs.com/maitian-lf/p/3782012.html