现在的位置: 首页 > 综合 > 正文

利用RewritePath和pathInfo实现URL重写及其优点

2013年05月10日 ⁄ 综合 ⁄ 共 2037字 ⁄ 字号 评论关闭
我们经常使用:RewritePath(string path);来实现URL重写 ,它还具有3个参数的重载形式RewritePath(string filePath, string pathInfo, string queryString);其中filePath是重写路径 , queryString是查询字符串, pathInfo这个参数比较有意思,是指附加到filePath的信息. 可以在请求页面使用Request.PathInfo获取该参数的值. 看以下的URL重写片段代码: (来自Cuyahoga)

原URL:        /14/section.aspx/ForumView/2
重写规则:     <add match="(\d+)\/section.aspx([\w|/]*)\??(.*)" replace="Default.aspx$2?SectionId=$1&amp;$3" />
重写后的URL:  /Default.aspx/ForumView/2?SectionId=14&

string rewritePath = Regex.Replace(urlToRewrite, matchExpression, UrlHelper.GetApplicationPath() + mappings[i],
RegexOptions.IgnoreCase 
| RegexOptions.Singleline);
//rewritePath的值为:/Default.aspx/ForumView/2?SectionId=14&
// MONO_WORKAROUND: split the rewritten path in path, pathinfo and querystring
// because MONO doesn't handle the pathinfo directly
//context.RewritePath(rewritePath);
string querystring = String.Empty;
string pathInfo = String.Empty;
string path = String.Empty;
// 1. extract querystring
int qmark = rewritePath.IndexOf("?");
if (qmark != -1 || qmark + 1 < rewritePath.Length)
{
    querystring 
= rewritePath.Substring (qmark + 1);//截取?号后面的查询字符串 SectionId=14&
    rewritePath = rewritePath.Substring (0, qmark);//  /Default.aspx/ForumView/2
}
// 2. extract pathinfo
int pathInfoSlashPos = rewritePath.IndexOf("aspx/"+ 4;//获取pathInfo的位置:"aspx/"后出现的字符串
if (pathInfoSlashPos > 3)//若存在"aspx/"
{
    pathInfo 
= rewritePath.Substring(pathInfoSlashPos);// pathInfo:"/ForumView/2"
    rewritePath = rewritePath.Substring(0, pathInfoSlashPos);// rewritePath:"/Default.aspx"
}
// 3. path
path = rewritePath;

//path : "/Default.aspx"
//pathInfo : "/ForumView/2"
//querystring : "SectionId=14&"

//执行重写
this._currentContext.RewritePath(path, pathInfo, querystring);
rewrittenUrl 
= path + pathInfo;
if (querystring.Length > 0)
{
    rewrittenUrl 
+= "?" + querystring;
}

    为什么不用RewritePath(rewritePath)直接进行重写呢? 通过pathInfo可以将URL的参数分为两个部分, 一部分是path+querystring , 一部分是pathInfo .
    这种方式对于基于模块构建的系统就非常有用. 系统的主干部分用path+querystring参数  , 子模块用pathInfo参数 . 这样可以在子模块中处理关于自己的URL参数,添加子模块时不需要在系统的web.config 中添加子模块的URL重写规则.
    还有一点 这样可以支持Mono.Created by jecray

抱歉!评论已关闭.