ASP.NET 2.0 中的URL 重写技术[转]

实现URL重写的几种方法?

l         利用Application_BeginRequestHttpContext类的Rewrite方法重写URL,这种方法比较简单易懂易用。

l         开发ASP.NET Http Module来达到同样的目的

l         开发ISAPI过滤器来截取请求完成重写

 

在这里,我们将就第一种方法来阐述URL重写的实现

Application_BeginRequest 事件

它是HTTP管线处理被激发的第一个事件,是重写URL的最佳地方

 

HttpContext

这个类包含有关Http的特定信息,其中有Http Request,当然也有Response对像。

这个类里面有一个Current静态属性,它里面包含当前应用程的信息。RewritePath方法是重写URL的关键。在2.0中有四个签名:

public void RewritePath(string path);

public void RewritePath(string path, bool rebaseClientPath);

public void RewritePath(string filePath, string pathInfo, string queryString);

public void RewritePath(string filePath, string pathInfo, string queryString, bool setClientFilePath);

 

按步就搬

 

1.         新建一个C# Web Application工程

2.         打开WEB配置文件,加入下列代码

ASP.NET 2.0 中的URL 重写技术[转]<appSettings>
ASP.NET 2.0 中的URL 重写技术[转]
<add key="productsSite" value="products"></add>
ASP.NET 2.0 中的URL 重写技术[转]
<add key="servicesSite" value="services"></add>
ASP.NET 2.0 中的URL 重写技术[转]
<add key="supportSite" value="support"></add>
ASP.NET 2.0 中的URL 重写技术[转]
</appSettings>
ASP.NET 2.0 中的URL 重写技术[转]

 

我们把相对应的文件夹名称放在这里,在后面的代码中将用到。

3.         在工程里添加三个文件夹,Products,Support Services

4.         在每个文件里面添加一个default.aspx页面

5.         打开Global.asax看看事件句柄

 

ASP.NET 2.0 中的URL 重写技术[转]protected void Application_BeginRequest(object sender, EventArgs e)

6.         把下面的代码加到上述事件里:


ASP.NET 2.0 中的URL 重写技术[转]            string host, originalurl, newurl;
ASP.NET 2.0 中的URL 重写技术[转]            host 
= Request.Url.Host;
ASP.NET 2.0 中的URL 重写技术[转]            originalurl 
= Request.Url.PathAndQuery;
ASP.NET 2.0 中的URL 重写技术[转]
ASP.NET 2.0 中的URL 重写技术[转]            
switch (host)
            HttpContext.Current.RewritePath(newurl);


 

  让我们再来看看这段代码:

 

首先我们用 Request.Url.Host 属性得到主机名,如:support.henryliu.com,其次还要获得当前路径的查询字符串。Switch语句我们用来根据当前用户的请求来判断真正要执行的页面请求。最后,我们调用RewritePath()方法重写当前请求的URL

 

总节:在这篇文章里我们可以学习到怎样用Application_BeginRequest HttpContext.RewritePah()来重写URL。这是一个快速实现实际请求页面和我们看到的URL不同的方法。

相关文章: