【转】Asp.net实现URL重写

【概述】html

URL重写就是首先得到一个进入的URL请求而后把它从新写成网站能够处理的另外一个URL的过程。重写URL是很是有用的一个功能,由于它可让你提升搜索引擎阅读和索引你的网站的能力;并且在你改变了本身的网站结构后,无须要求用户修改他们的书签,无需其余网站修改它们的友情连接;它还能够提升你的网站的安全性;并且一般会让你的网站更加便于使用和更专业。web

【过程】浏览器

实现安全

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

二、 在解决方案中先添加一个【类库】项目: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网站

三、在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>

关于配置文件的说明:url

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

在 经典模式 下,配置文件须要将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>

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

四、测试

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

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

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

相关文章
相关标签/搜索