-
在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,可以看到如下的效果:
时间: 2024-10-10 22:29:42