原文:Asp.net实现URL重写

【概述】

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

【过程】

 
【方法】
1、在asp.net请求管道中重写路径
2、通过组件,如微软的UrlRewriter.dll
 
【介绍】
1、在asp.net请求管道中重写路径
要重写,首先是截获客户端请求的URL,然后分析当时的URL,最后跳转到相应的页面。这里通过自定义HttpModule来截获URL请求,并通过正则来实现URL的解析,然后转换成网站能识别的路径。
a) 在解决方案中先添加一个【类库】项目:UrlReWriter,在项目中添加类:MyUrlWriter,该类继承IHttpModule接口,代码如下:
      class MyUrlWriter : IHttpModule
{
public void Init( HttpApplication context)
{
context.BeginRequest += new EventHandler (context_BeginRequest);
} protected void context_BeginRequest( object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication ;
HttpContext context = application.Context; //上下文
string url = context.Request.Url.LocalPath; //获得请求URL Regex articleRegex = new Regex ("/Article/[A-Z0-9a-z_]+" ); //定义规则
if (articleRegex.IsMatch(url))
{
string paramStr = url.Substring(url.LastIndexOf('/' ) + );
context.RewritePath( "/Article.aspx?id=" + paramStr);
}
else
{
context.RewritePath( "/Default.aspx" );
}
} public void Dispose() { }
}
b) 在解决方案中添加一个网站项目,在引用中添加UrlReWriter的项目引用,然后在web.config中将自定义的HttpModule注册进去,代码如下:
   <httpModules >
<add name = "UrlReWriter " type =" UrlReWriter.MyUrlWriter,UrlReWriter " />
</httpModules >
c) 然后添加一个Article.aspx页面,在Article.aspx.cs类中添加输出语句,代码如下:
       public partial class Article : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e)
{
Response.Write(Request.QueryString[ "id" ]);
}
}
d) 最后在Default.aspx页面中添加测试链接,代码如下:
 <a href ="/Article/35">测试url重写</a>
e) 项目截图如下:
f) 按【F5】运行,打开Default.aspx页,如下:
g) 点击后转到Article.aspx页面,实现重写,如下:
2、通过组件,如微软的UrlRewriter.dll
这个组件的原理和我们自定义HttpModule的原理一样,也是进入管道后拦截BeginRequest请求,然后将配置文件中的路径规则(正则表达式)引用过来,然后对请求的路径按正则进行替换成网站识别的路径。这个组件的核心代码(未翻译)如下:

      
     /// <summary>
/// Provides a rewriting HttpModule.
/// </summary>
public class ModuleRewriter : BaseModuleRewriter
{
/// <summary>
/// This method is called during the module's BeginRequest event.
/// </summary>
/// <param name="requestedRawUrl"> The RawUrl being requested (includes path and querystring).</param>
/// <param name="app"> The HttpApplication instance. </param>
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 rules
RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules; // iterate through each rule...
for (int i = ; 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 found
if (re.IsMatch(requestedPath))
{
// match found - do any replacement needed
string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath,re.Replace(requestedPath, rules[i].SendTo)); // log rewriting information to the Trace object
app.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 object
app.Context.Trace.Write( "ModuleRewriter" , "Exiting ModuleRewriter");
}
}
a) 先想办法得到一个UrlRewriter.dll,通过http://download.microsoft.com/download/0/4/6/0463611e-a3f9-490d-a08c-877a83b797cf/MSDNURLRewriting.msi下载。下载得到的是一个用vs2003开发的源文件,可以用vs2008或者更高版本编译器转换后,生成解决方案,在bin目录中生成UrlRewriter.dll文件。
b) 新建一个网站项目,添加引用第一步产生的UrlRewriter.dll文件,添加Article.aspx、News.aspx页面。
c) 在Article.aspx后台代码中添加一行输出方法,代码如下:
       public partial class Article : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e)
{
Response.Write(Request.QueryString[ "id" ]);
}
}
d) 在News.aspx后台代码中添加一行输出方法,代码如下:
      public partial class News : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e)
{
Response.Write( string .Format("日期:{0}<br/>" , Request.QueryString["date" ]));
Response.Write( string .Format("ID:{0}<br/>" , Request.QueryString["id" ]));
}
}
e) 打开web.config文件,在节点<configSections>中添加一个<section>节点,代码如下:
     <configuration>
<configSections>
<section name = "RewriterConfig " type =" URLRewriter.Config.RewriterConfigSerializerSectionHandler,URLRewriter " />
</configSections>
</configuration>
f) 在<httpHandlers>节点中加入后缀判定规则,代码如下:
     <httpHandlers>
<remove verb = "* " path = "*.asmx " />
<add verb = "* " path = "* " type = "URLRewriter.RewriterFactoryHandler, URLRewriter" />
<add verb = "* " path = "*.html " type =" URLRewriter.RewriterFactoryHandler, URLRewriter " />
</httpHandlers>
g) 在节点中配置URL规则,代码如下:
     <configuration>
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>~/Article/([A-Z0-9a-z_]+) </LookFor>
<SendTo>~/Article.aspx?id=$1 </SendTo>
< RewriterRule>
<RewriterRule>
<LookFor>~/News/(\d{4}-\d{2}-\d{2})/(\d{1,6})\.html? </LookFor>
<SendTo>~/News.aspx?date=$1 &amp; id=$2</SendTo>
</RewriterRule>
</Rules>
</RewriterConfig>
</configuration>
LooFor节点表示与请求URL匹配的路径正则,SendTo表示转换后的地址规则,$1表示LookFor正则中第一个括号匹配得到的值,$2表示LookFor正则中第二个括号匹配得到的值,熟悉正则的朋友都知道这个。
h) 最后在Default.aspx页面中添加两个测试链接,代码如下:
         <a href ="<% = ResolveUrl("Article/35")%> "> 测试文章url重写</a>< br />
<a href ="<% = ResolveUrl("News/2014-06-11/285864.html")%> "> 测试新闻url重写</a>
i) 按【F5】运行,打开Default.aspx页,如下:
j) 点击“测试文章url重写”,如下:
k) 点击“测试新闻url重写”,如下:
 
【总结】
这个知识点很简单,很多大牛们也写过,这篇文章也参考了几位高手的博客,然后自己写了两个demo。
有些东西,你能写出来和表述出来才能说你会了。
希望对大家有帮助,谢谢支持。
 

Asp.net实现URL重写的更多相关文章

  1. ASP.net的url重写

    http://blog.csdn.net/windok2004/article/details/2432691 1. 有关于URL的重写,本文也只是拿来主意.相继有MS的组件“URLRewriter” ...

  2. ASP.NET MVC URL重写与优化(1)-使用Global路由表定制URL

    ASP.NET MVC URL重写与优化(1)-使用Global路由表定制URL 引言--- 在现今搜索引擎制霸天下的时代,我们不得不做一些东西来讨好爬虫,进而提示网站的排名来博得一个看得过去的流量. ...

  3. asp.net 页面url重写

    不更改情况下,页面路径为index.aspx?id=1,现在输入页面路径index/1时,也能访问到页面,这一过程叫做url重写 ①:在一个类里制定路径重写规则,以下为自定义UrlRewriterFi ...

  4. (转)ASP.net的url重写

    1. 有关于URL的重写,本文也只是拿来主意.相继有MS的组件“URLRewriter”和在Global.asax里的“Application_BeginRequest()”编码方式,以及IIS里的I ...

  5. ASP.NET MVC URL重写与优化(进阶篇)-继承RouteBase

    原文地址:http://www.51csharp.com/MVC/882.html   ASP.NET MVC URL重写与优化(进阶篇)-继承RouteBase玩转URL 引言-- 在初级篇中,我们 ...

  6. ASP.NET MVC URL重写与优化(初级篇)-使用Global路由表定制URL

    ASP.NET MVC URL重写与优化(初级篇)-使用Global路由表定制URL 引言--- 在现今搜索引擎制霸天下的时代,我们不得不做一些东西来讨好爬虫,进而提示网站的排名来博得一个看得过去的流 ...

  7. ASP.NET MVC URL重写与优化(进阶篇)-继承RouteBase玩转URL

    http://www.cnblogs.com/John-Connor/archive/2012/05/03/2478821.html 引言-- 在初级篇中,我们介绍了如何利用基于ASP.NET MVC ...

  8. [转载]ASP.NET MVC URL重写与优化(进阶篇)-继承RouteBase玩转URL

    引言-- 在初级篇中,我们介绍了如何利用基于ASP.NET MVC的Web程序中的Global文件来简单的重写路由.也介绍了它本身的局限性-依赖于路由信息中的键值对: 如果键值对中没有的值,我们无法将 ...

  9. 【转】Asp.net实现URL重写

    [概述] URL重写就是首先获得一个进入的URL请求然后把它重新写成网站可以处理的另一个URL的过程.重写URL是非常有用的一个功能,因为它可以让你提高搜索引擎阅读和索引你的网站的能力:而且在你改变了 ...

随机推荐

  1. iOS_18_开关控制器_NavigationController_push道路_数据传输

    最后效果图: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlX2VtaW5lbnQ=/font/5a6L5L2T/fontsize/400/fill ...

  2. 【转】linux建立软链接

    实例:ln -s /home/gamestat    /gamestat linux下的软链接类似于windows下的快捷方式 ln -s a b 中的 a 就是源文件,b是链接文件名,其作用是当进入 ...

  3. 成不了天才,但为何也没成"人材"?(转)

    长期以来,"软件业"一直被视为"智力密集"型的"朝阳"产业,大多数从业者都受过高等教育,其平均素质居于社会各行业的前列,这个产业的顶尖人物被 ...

  4. 数据库管理——Powershell——使用Powershell脚本找出消耗最多磁盘空间的文件

    原文:数据库管理--Powershell--使用Powershell脚本找出消耗最多磁盘空间的文件 原文译自: http://www.mssqltips.com/sqlservertip/2774/p ...

  5. 他们控制的定义-DragButton

    一个.叙述性说明 可拖动Button 两.无图无真相 这是用在实际工程效果图.和demo不太一样. 三.源代码 https://github.com/mentor811/Demo_DragButton ...

  6. Python脚本传參和Python中调用mysqldump

    Python脚本传參和Python中调用mysqldump<pre name="code" class="python">#coding=utf-8 ...

  7. php用空格代替标点符号

    php作为常规赛的符号替换为空格 <? php $character = "!@#$%^&*于'纸'纸'文().,<>|[]'\":;}{-_+=? /a ...

  8. 写自己的第二级处理器(3)——Verilog HDL行为语句

    我们会继续上传新书<自己动手写处理器>(未公布),今天是第七章,我每星期试试4 2.6 Verilog HDL行为语句 2.6.1 过程语句 Verilog定义的模块一般包含有过程语句,过 ...

  9. MySQL SQL分析(SQL profile)

    分析SQL优化运营开销SQL的重要手段.在MySQL数据库.可配置profiling参数启用SQL分析.此参数可以在全局和session水平集.级别则作用于整个MySQL实例,而session级别紧影 ...

  10. 解决 configure.ac:17: error: possibly undefined macro: AC_PROG_LIBTOOL

    当安装configure.ac:17: error: possibly undefined macro: AC_PROG_LIBTOOL If this token and others are le ...