利用RewritePath和pathInfo实现URL重写及其优点
2009-07-04 23:22
344 查看
利用RewritePath和pathInfo实现URL重写及其优点
我们经常使用: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&$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重写规则.
相关文章推荐
- 利用RewritePath和pathInfo实现URL重写及其优点
- 利用RewritePath和pathInfo实现URL重写及其优点
- RewritePath() 实现简单高效的URL重写代码
- RewritePath() 实现简单高效的URL重写。
- 利用openfire及其connection manager实现大容量web im的架构设想
- 利用Apache的rewrite实现URL的伪静态化
- 在ASP.NET中如何实现和利用URL重写(转)
- 转:ASP.NET 2.0利用Httphandler实现URL重写(伪URL及伪静态)
- java代码实现利用 classloader 动态加载 jar包、文件夹到classpath中
- SQL Server 中利用STUFF和FOR XML PATH()实现多行数据的拼接
- ASP.NET2.0利用httphandler实现URL重写(伪URL及伪静态)
- wordpress在IIS下无rewrite利用cos-html-cache实现静态页面
- Nginx php下实现rewrite和pathinfo
- 利用ViewPager实现3D画廊效果及其图片加载优化
- 利用URL重写实现参数目录化
- 利用URL重写实现参数目录化
- 利用stuff函数,for xml path('') 实现列的合并
- 利用httpd.ini和.htaccess的Rewrite实现301域名重定向
- 介绍一下我利用Url重写实现的松耦合框架