首页 > 技术文章 > 【转】Asp.net实现URL重写

fnz0 2017-11-21 17:58 原文

【概述】

URL重写就是首先获得一个进入的URL请求然后把它重新写成网站可以处理的另一个URL的过程。重写URL是非常有用的一个功能,因为它可以让你提高搜索引擎阅读和索引你的网站的能力;而且在你改变了自己的网站结构后,无需要求用户修改他们的书签,无需其他网站修改它们的友情链接;它还可以提高你的网站的安全性;而且通常会让你的网站更加便于使用和更专业。

【过程】

实现

1、新建一个 【ASP.NET 空Web应用程序】项目:WebApp,并添加一个1.html的文件

2、 在解决方案中先添加一个【类库】项目:UrlReWriter,在项目中添加类:MyHttpModule,该类继承IHttpModule接口,代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Text.RegularExpressions;
 6 using System.Web;
 7 
 8 namespace UrlReWriter
 9 {
10     public class MyHttpModule : IHttpModule
11     {
12         public void Init(HttpApplication context)
13         {
14             context.BeginRequest += new EventHandler(ContextOnBeginRequest);
15         }
16 
17         private void ContextOnBeginRequest(object sender, EventArgs eventArgs)
18         {
19             HttpApplication application = sender as HttpApplication;
20             HttpContext context = application.Context;
21             string url = context.Request.Url.LocalPath;
22 
23             Regex reg = new Regex(@"(.*)?\.haha$"); 
24             if (reg.IsMatch(url))
25             {
26                 context.RewritePath(reg.Replace(url,"$1.html"));
27             }
28         }
29 
30         public void Dispose()
31         {
32             throw new NotImplementedException();
33         }
34     }
35 
36 }

可以看出此类的作用是将后缀为.haha的请求路径重写为.html

3、在WebApp项目中添加UrlReWriter项目的引用,并在WebApp项目中的Web.config文件中添加如下配置(红色部分为添加的)

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

<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.webServer>
      <modules>
        <add name="UrlReWriter" type="UrlReWriter.MyHttpModule,UrlReWriter"/>
      </modules>
    </system.webServer>
</configuration>

关于配置文件的说明:

IIS应用程序池有两种模式,一种是“集成模式”,一种是“经典模式”。

在 经典模式 下,配置文件需要将httpModules节点添加到system.web节点中,而在集成模式下,需要将httpModules节点改为modules节点,并放到system.webServer节点中。

即:再经典模式下的配置文件应该这样写(红色部分为添加):

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

<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <httpModules>
        <add name="UrlReWriter" type="UrlReWriter.MyHttpModule,UrlReWriter"></add>
      </httpModules>
    </system.web>
</configuration>

如果是集成方式,请用第一种配置文件

4、测试

再浏览器中输入地址http://localhost:31872/1.haha

因为在管道中拦截了此次请求,并将地址重写为http://localhost:31872/1.html,所以最终会将1.html页面返回给浏览器。

原文链接:https://www.cnblogs.com/maitian-lf/p/3782012.html

 

推荐阅读