ASP.NET伪静态实现

在asp.net下,如何自己写代码来实现伪静态呢?如何重写url地址呢?


例如:本来aspx的页面地址是:/default.aspx?id=1,我要重写成这样:/index-1.html。那如何实现?


思路如下:利用HttpModule来实现。


1.新建文件,URLHttpModel.cs,并实现IHttpModule接口。代码如下:

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,代码如下:

<httpModules>
      <add name="URLModel" type="Web.HttpModel.Demo.URLHttpModel,Web.HttpModel.Demo"/>
</httpModules>

3,然后运行项目,输入如下地址,/index-1.html,可以看到如下的效果:



发布了40 篇原创文章 · 获赞 239 · 访问量 30万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章