• 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>
    

    测试结果:

  • 相关阅读:
    PHP的错误和异常处理
    异步并行批处理框架设计的一些思考
    系统出错信息设计
    SpringMVC+Shiro权限管理
    jstl教程
    为什么Lisp语言如此先进
    「只差程序员」为什么会招黑? [转自:知乎]
    大侠是怎样炼成的 周昆 [转]
    【OpenGL】glFinish()和glFlush()函数详解-[转]
    VC++ 6.0中实现三叉切分窗口与多视图 [转]
  • 原文地址:https://www.cnblogs.com/surfing/p/3544587.html
Copyright © 2020-2023  润新知