標籤:bsp toc ref system end tracking namespace pattern efault
-
在asp.net下,如何自己寫代碼來實現偽靜態呢?如何重寫url地址呢?
例如:本來aspx的頁面地址是:/default.aspx?id=1,我要重寫成這樣:/index-1.html。那如何??
思路如下:利用HttpModule來實現。
1.建立檔案,URLHttpModel.cs,並實現IHttpModule介面。代碼如下:
[csharp] view plain copy
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text.RegularExpressions;
- using System.Web;
-
- namespace Web.HttpModel.Demo
- {
- public class URLHttpModel : IHttpModule
- {
- public void Init(HttpApplication context)
- {
- context.BeginRequest += Context_BeginRequest;
- }
-
- private void Context_BeginRequest(object sender, EventArgs e)
- {
- HttpApplication app = (HttpApplication) sender;
- HttpContext context = app.Context;
- string requestPage = context.Request.Path.ToLower();
- var newPattern = "/index-(\\d+).html";
- if (Regex.IsMatch(requestPage, $"^{newPattern}$", RegexOptions.None | RegexOptions.IgnoreCase))
- {
- string queryString = Regex.Replace(requestPage, newPattern, "id=$1", RegexOptions.None | RegexOptions.IgnoreCase);
- context.RewritePath("/Default.aspx", string.Empty, queryString);
- }
- }
-
- public void Dispose()
- {
-
- }
- }
- }
2.然後在web.config檔案中,配置此Modeule,代碼如下:
[csharp] view plain copy
- <httpModules>
- <add name="URLModel" type="Web.HttpModel.Demo.URLHttpModel,Web.HttpModel.Demo"/>
- </httpModules>
3,然後運行項目,輸入如下地址,/index-1.html,可以看到如下的效果:
ASP.NET偽靜態實現