Asp.Net通过HttpModule实现URL重写

首先总结一下为什么要对URL进行Rewrite,比如我可以把/Default.aspx?param=3替换成/Home/Default/3(类似mvc)。

    一、缩短url,隐藏实际路径提高安全性;

    二、易于用户记忆和键入;

    三、易于被搜索引擎收录.

这里就不谈缺点了,本身这也只是个简单的demo,这里是通过webform模拟mvc,然后再通过/Home/Default/3这种的url来还原真正的url。都知道asp.net的事件可以分为三种:应用程序级别的事件、页面级别的事件和控件级别的事件。显然对url的重写应写到应用程序级别的事件中,而HttpModule又是httpRequest的必经之路,在此做文章再好不过!

第一步、创建httpModule,代码:

namespace WebApplication1
{
    public class ModuleForUrlRewriting : IHttpModule
    {
        public void Dispose()
        {

        }
        public void contextBeginRequest(object sender, EventArgs e)
        {
            HttpApplication httpApplication = sender as HttpApplication;
            var originUrl = httpApplication.Request.RawUrl;
            string[] strElements = originUrl.Split(new char[] { '/' });
            if (strElements.Contains("Home"))
            {
                var newUrl = strElements.Length == 3 ? ("/" + strElements[2] + ".aspx") : ("/" + strElements[2] + ".aspx" + "?param=" + strElements[3]);
                httpApplication.Context.RewritePath(newUrl);
            }
        }
        public void Init(HttpApplication context)
        {
            //关联请求开始事件  
            context.BeginRequest += new EventHandler(contextBeginRequest);
        }
    }
}

第二步、在webconfig中配置HttpModule

<httpModules>
      <add name="ModuleForUrlRewriting" type="WebApplication1.ModuleForUrlRewriting,WebApplication1"/>
    </httpModules>

测试结果:

原文地址:https://www.cnblogs.com/surfing/p/3544587.html