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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章