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,可以看到如下的效果:



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值