zoukankan      html  css  js  c++  java
  • 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>
    

    测试结果:

  • 相关阅读:
    Docker 介绍
    Docker 教程
    Python 删除文件与文件夹
    Python 读文件
    Python 打开文件(File Open)
    Python 异常处理(Try...Except)
    什么是拜占庭将军问题
    智能合约语言 Solidity 教程系列7
    给代币添加高级功能-代币管理、增发、兑换、冻结等
    一步步教你创建自己的数字货币(代币)进行ICO
  • 原文地址:https://www.cnblogs.com/surfing/p/3544587.html
Copyright © 2011-2022 走看看