一、URL重写概念
URL重写就是首先获得一个进入的URL请求然后把它重新写成网站可以处理的另一个URL的过程。重写URL是非常有用的一个功能,因为它可以让你提高搜索引擎阅读和索引你的网站的能力;而且在你改变了自己的网站结构后,无需要求用户修改他们的书签,无需其他网站修改它们的友情链接;它还可以提高你的网站的安全性;而且通常会让你的网站更加便于使用和更专业。
二、URL重写方法
目前url重写最常见的两种方法有:
1、在asp.net请求管道中重写路径
2、通过组件,如微软的UrlRewriter.dll
1、在asp.net请求管道中重写路径
2、通过组件,如微软的UrlRewriter.dll
三、在asp.net请求管道中重写URL
要重写,首先是截获客户端请求的URL,然后分析当时的URL,最后跳转到相应的页面。这里通过自定义HttpModule来截获URL请求(在请求管道中的第一个事件中拦截url并使其完成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('/' ) + 1);
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>
f) 按【F5】运行,打开Default.aspx页,如下:
g) 点击后转到Article.aspx页面,实现重写,如下:
四、通过组件,如微软的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 = 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 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>
<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 & 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重写”,如下: