概述

今天看了下URL重写的实现,主要看的是MS 的URL Rewrite。

URL重写的优点有:更友好的URL,支持老版本的URL

URL重写的缺点有:最主要的缺点是性能低下,因为如果要支持无后缀的URL(但更多的情况是我们要支持这种方式)就必须在IIS中配置所有的URL(包括js,css,image)都要转发到aspnet_isapi中,解决方法可以参见 慎用url重写;还有一个性能问题是,根据源代码,在匹配url时,用正则表达式尝试匹配每一个规则,直至有一个匹配成功,或都匹配不成功才结束。那么那些不需要重写的URL,就要将所有的正则表达式都要执行一次,可以在进入匹配之前先做一个判断,排除掉一些情况

1 配置 web.config

1.1 下载 MS的URLRewrite

地址是:http://download.microsoft.com/download/0/4/6/0463611e-a3f9-490d-a08c-877a83b797cf/MSDNURLRewriting.msi

1.2 配置自定义section的声明节点

  <configSections><section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" /></configSections>

1.3 配置自定义section的内容

用UrlRewrite在完成配置后,主要的工作就是写配置url映射的正则表达式了。对于正则式不清楚的人,可以看看这个正则表达式入门及备忘

  <RewriterConfig><Rules><RewriterRule><LookFor>~/pick/?</LookFor><SendTo><![CDATA[~/pick.aspx]]></SendTo></RewriterRule><RewriterRule><LookFor>~/pick/(\d+)</LookFor><SendTo><![CDATA[~/pick.aspx?page=$1]]></SendTo></RewriterRule><RewriterRule><LookFor>~/(\w+)/p/(\d+).html</LookFor><SendTo><![CDATA[~/BlogDetails.aspx?blogwriter=$1&blogid=$2]]></SendTo></RewriterRule><RewriterRule><LookFor>~/Product/(\w{4}).html</LookFor><SendTo>~/Product.aspx?id=$1</SendTo></RewriterRule></Rules></RewriterConfig>

1.4 配置httpmodules或httphandlers

在如果是旧的IIS 6.0,在<system.web>节点下配置,httpmodules和httphandlers只需要一个就好,用于拦截所有请求

    <httpModules><add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" /></httpModules><!--<httpHandlers><add verb="*" path="*.aspx" type="URLRewriter.RewriterFactoryHandler, URLRewriter" /></httpHandlers>-->

在新的IIS7.0中, 在<system.webServer>节点下配置, modules 和handlers同样只需要一个

  <system.webServer><modules><add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" /></modules><!--<handlers><add verb="*" path="*.*" type="URLRewriter.RewriterFactoryHandler, URLRewriter" name="URLRewriter" /></handlers>--></system.webServer>

1.5 配置IIS

在发布到IIS后,如果访问路径出错,需要做一下扩展名的映射。额,我用的IIS7.0是没有报错,直接就可访问了。

2 代码分析

UrlRewrite的源代码十分的简单,实际上就是实现了一个IHttpModule的接口来拦截所有的请求URL。然后,将请求的URL用正则表达式与每一个匹配,直到有一个匹配成功,则将原有的url(假的)根据正则表达式转成实际的url。如果都匹配不成功,则按原有的路径处理请求

主要代码是

protected override void Rewrite(string requestedPath, System.Web.HttpApplication app){// log information to the Trace object.app.Context.Trace.Write("ModuleRewriter", "Entering ModuleRewriter");// get the configuration rulesRewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;// iterate through each rule...for(int i = 0; i < rules.Count; i++){// get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$";// Create a regex (note that IgnoreCase is set...)Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);// See if a match is foundif (re.IsMatch(requestedPath)){// match found - do any replacement neededstring sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].SendTo));// log rewriting information to the Trace objectapp.Context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl);// Rewrite the URL
                    RewriterUtils.RewriteUrl(app.Context, sendToUrl);break;        // exit the for loop
                }}// Log information to the Trace objectapp.Context.Trace.Write("ModuleRewriter", "Exiting ModuleRewriter");}

View Code

看了这个源代码,还学到的一个东西就是在web.config中自定义节点,然后实现一下IConfigurationSectionHandler 接口,将section的内容转成对象,在程序中使用,主要代码有:

        public static RewriterConfiguration GetConfig(){if (HttpContext.Current.Cache["RewriterConfig"] == null)HttpContext.Current.Cache.Insert("RewriterConfig", ConfigurationManager.GetSection("RewriterConfig"));return (RewriterConfiguration) HttpContext.Current.Cache["RewriterConfig"];}/// <summary>/// Deserializes the markup in Web.config into an instance of the <see cref="RewriterConfiguration"/> class./// </summary>public class RewriterConfigSerializerSectionHandler : IConfigurationSectionHandler {/// <summary>/// Creates an instance of the <see cref="RewriterConfiguration"/> class. : IConfigurationSectionHandler /// </summary>/// <remarks>Uses XML Serialization to deserialize the XML in the Web.config file into an/// <see cref="RewriterConfiguration"/> instance.</remarks>/// <returns>An instance of the <see cref="RewriterConfiguration"/> class.</returns>public object Create(object parent, object configContext, System.Xml.XmlNode section) {// Create an instance of XmlSerializer based on the RewriterConfiguration type...XmlSerializer ser = new XmlSerializer(typeof(RewriterConfiguration));// Return the Deserialized object from the Web.config XMLreturn ser.Deserialize(new XmlNodeReader(section));}}

View Code

3 最后

最后就是,UrlReWrite虽然好用,但是根据这源代码,性能问题是个大头,但平常自己的小网站用用还是没问题的,如果请求量大了,也知道这里UrlRewrite这里有问题,可以用httphander的方式只拦截特定的url,也可以用IIS filter去搞(没搞过,但应该能用,毕竟是在IIS端拦截大部分的请求,而不是将求放到扩展程序中去)。关于IIS filter可以参考这个文章  在 ASP.NET 中执行 URL 重写

UrlRewrite(URL重写)--ASP.NET中的实现相关推荐

  1. UrlRewrite(Url重写技术)

    ASP.NET伪静态 UrlRewrite(Url重写) 实现和配置------转载 ASP.NET伪静态 UrlRewrite(Url重写) 实现和配置 核心提示:大家一定经常在网络上看到很多网站的 ...

  2. ASP.NET伪静态 UrlRewrite(Url重写) 实现和配置

    核心提示:大家一定经常在网络上看到很多网站的地址后缀都是用XX.HTML或者XX.ASPX等类似静态文件的标示来操作的吧,那么大家有怀疑过他真的是一个一个的静态生成的文件么,静态文件的生成的优缺有好有 ...

  3. java urlrewrite_Java|urlrewrite|URL重写|多个参数

    1.0  web -info 目录下建立     urlrewrite.xml  文件 类似如下: View Source for full doctype...)> - - ^/morednf ...

  4. IIS URLReWrite URL 重写模块 下载地址

    https://www.microsoft.com/zh-cn/download/details.aspx?id=7435 转载于:https://www.cnblogs.com/fuqiang88/ ...

  5. tp3 普通模式url模式_[tp3.2.1]开启URL(重写模式),省略URL中的index.php

    重写模式(省略url中的index.php) 在apache配置文件httpd.conf中,查找 1.mod_rewrite.so, 启动此模块 2.AllowOverride , 值= All 3. ...

  6. camel.js_Camel 2.11 –具有URL重写功能的HTTP代理路由

    camel.js 在即将发布的Apache Camel 2.11版本中,我最近添加了对将自定义url重写实现插入基于HTTP的路由(http,http4,jetty)的支持. 当您使用骆驼代理/桥接H ...

  7. Camel 2.11 –具有URL重写功能的HTTP代理路由

    在即将发布的Apache Camel 2.11版本中,我最近添加了对将自定义url重写实现插入基于HTTP的路由(http,http4,jetty)的支持. 当您使用骆驼代理/桥接HTTP路由时,这使 ...

  8. php rewrite url_PHP实现url重写和.htaccess

    .htaccess是一个完整的文件名(只有后缀),它是用于Apache服务器下的配置文件,当.htaccess文件放在某一文件夹下,它仅对该文件夹下的文件和文件夹有效.通过.htaccess文件,可以 ...

  9. ASP.NET 中执行 URL 重写

    作者:overred   来源:原创 URL 重写就是把URL地址重新改写(汗^_^). 详情:http://www.microsoft.com/china/msdn/library/webservi ...

最新文章

  1. python提高办公效率-几个可以提高工作效率的Python内置小工具
  2. 华科研究生复试机试题代码堆积供以后参考
  3. 基于Eclipse搭建STM32开源开发环境
  4. python8个程序语言_所有程序员必知--2019年最流行的8种编程语言和框架
  5. Retrofit使用
  6. lt;转载自刘佳ID:freedom0203和waretgt; C++中成员初始化列表的使用
  7. 解压速度更快, Zstandard 1.4.1 发布
  8. 公共代码参考(PackageManager)
  9. 谈谈 MVX 中的 Model
  10. vue 组件中图片地址,图片获取
  11. Hadoop退出安全模式
  12. 日志显示格式%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n
  13. 教您在CorelDRAW中安装字体
  14. Apollo Cyber RT学习手册(基于Ubuntu18.04、Apollo 6.0_edu)
  15. 这是我见过最完整的Spring全家桶学习笔记,没有之一!
  16. 图片怎么压缩到100k以下?
  17. 用Visual C# 2005创建快捷方式
  18. win11怎么查看隐藏文件
  19. 抖音测试距离的软件,抖音测量长度的软件如何使用?抖音测距仪使用方法介绍...
  20. chatterbot mysql_Chatbot Tutorial (聊天机器人制作教程) 每日更新 不断学习

热门文章

  1. NVIDIA各个领域芯片现阶段的性能和适应范围
  2. 图形操作类CBitmap 把内存数据输出到PIC控件
  3. Dynamics CRM Odata QueryUrl中的SetName问题
  4. Spring Boot 动态注入的两种方式
  5. solidity智能合约[7]-整型与运算
  6. 菜鸟学SSH(八)——Hibernate对象的三种状态
  7. 拿访问网站用户IP 纯JS实现
  8. 玻璃体浑浊的分子原理
  9. 2019宁波最重视的行业
  10. win7+ubuntu19.10使用easybcd安装