HttpModule入门

关于asp.net生命周期的文章,在园子里面已经有好多大牛写了。本想引用曾经在园子里面一个人的文章,一时之间找不到了,只好贴出那篇文章中的一幅图了。

由上面的铺垫,今天可以开始第一个URLRewrite程序了。

  • 首先我们先创建一个类MyhttpModule.cs
  • 然后配置Web.config(可以理解为添加对自定义的httpmodule的注册信息)
  • 自定义一个正则表达式,URLRewrite中最重要的工具就是正则表达式。这里我的示例:将"http://localhost:1539/Articles/AJAX-PHP-Book-Review.htm"重定向“http://localhost:1539/Product.aspx?ProductID=35”

MyhttpModule.cs如下:

 public class MyhttpModule:IHttpModule
    {
        Regex reg = new Regex("/Articles/(.+)$");
        public void Dispose()
        {
            
        }

        public void Init(HttpApplication context)
        {
            //这个Init方法功能是用来订阅事件,可以理解为过滤器作用。来处理一些请求信息。
           //并且每个请求都会经过这个方法。
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            Match match = reg.Match(context.Request.FilePath);
            if (match.Groups.Count<2)//不匹配match.Groups.Count=1
            {
                return;
            }
            //如果有一个匹配,就取出匹配的结果。
            string pageName = match.Groups[1].Value;

            if (pageName.ToLower() == "ajax-php-book-review.htm")
            {
                context.RewritePath("~/Product.aspx?ProductID=35");
            }
            else
            {
                context.Response.Status = "404 NOT FOUND";
            }
        }
    }

 接着就是Web.config配置

 <httpModules>
        <add name="MyhttpModule" type="UrlRewriter.MyhttpModule,UrlRewriter"/>
</httpModules>

 这里意思就是调用UrlRewriter.dll中的UrlRewriter.MyhttpModule来处理请求。(UrlRewriter为我的项目名称)

然后为了可以看到是否起作用了我们还要建一个Product.aspx。因为最终我们会重定向到这个页面。

     protected void Page_Load(object sender, EventArgs e)
        {
            string productId = this.Request["ProductID"];
            if (!string.IsNullOrEmpty(productId))
            {
                Response.Write(productId);
            }
        }

最后一步就是打开浏览器----》输入:“http://localhost:1539/Articles/AJAX-PHP-Book-Review.htm”

就可一看到结果为:页面上输出一个35.但是我们请求的URL还是“http://localhost:1539/Articles/AJAX-PHP-Book-Review.htm”。

这样就可以达到SEO优化的目的,这里演示只是原理的一部分。要到达真正的URLRewrite需要建立一个双向解析的机制,不像这里写死了规则。写死规则只是为了方便探究原理。

原文地址:https://www.cnblogs.com/hankskfc/p/2261244.html