使用IHttpModule实现简单的页面重映射Url

原理: HttpModule模块在任何请求发生时都会执行,所有可以在该类中执行Url的重映射跳转

第一步:定义IHttpModule

public class UrlRemapper : IHttpModule

{

 

    public void Init(HttpApplication context)

    {

        context.BeginRequest += new EventHandler(context_BeginRequest);

    }

 

    void context_BeginRequest(object sender, EventArgs e)

    {

        HttpApplication app = (HttpApplication)sender;

        HttpContext context = app.Context;

  //获取当前请求页面

        string currentUrl = context.Request.AppRelativeCurrentExecutionFilePath;

        //获取包含映射关系的xml文件

        XmlDocument doc = GetUrlMapperings(context);

        XmlNodeList nodes = doc.SelectNodes("//add");

        foreach (XmlNode item in nodes)

        {

            string url = item.Attributes["url"].Value;

            string mapperUrl = item.Attributes["mappedUrl"].Value;

            if (Regex.Match(currentUrl, url, RegexOptions.IgnoreCase).Success)

            {

//如果请求页面包含在映射关系内,则跳转页面

                context.RewritePath(mapperUrl);           

 }

        }

    }

 

    private XmlDocument GetUrlMapperings(HttpContext context)

    {

        XmlDocument doc = new XmlDocument();

        doc.Load(context.Server.MapPath("~/UrlMappings.xml"));

 

        return doc;

    }

 

    public void Dispose()

    {

        //throw new NotImplementedException();

    }

}

 

第二步:在Web.config中注册IHttpModule

 <system.web>

      <httpModules>

        <add name="UrlRemapper" type="UrlRemapper" />

      </httpModules>

    </system.web>

 

 

IIS7以上注册:

<system.webServer>

<modules>

<add name="任意名称" type="命名空间.类名"/>
</modules>

</system.webServer>

第三步:将映射关系存放在XML文件中

<?xml version="1.0" encoding="utf-8" ?>

<urlMappings>

  <add url="~/HomeSource.aspx" mappedUrl="~/HomeTo.aspx"/>

  <!--<add url="~/HomeSource.aspx" mappedUrl="~/HomeTo.aspx"/>-->

</urlMappings>

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值