动网论坛,站长建站首选,国内使用量最多的论坛软件 动网论坛官方技术讨论区 站长工具 申请属于您自己的免费论坛
首页 | 新闻资讯 | 网站运营 | 网络编程 | 数据库 | 服务器 | 网页设计 | 图像媒体 | 网络应用 | 搜索优化 | 资源下载 | 动网主机 | DVBOX
    本站内  互联网 ASP论坛  ASP.Net论坛  PHP论坛
   .Net → 阅读文章

 asp.net 2.0中的URL重写以及urlMappings问题

作者来源: 
阅读 数 244 人次 , 2006-4-26 9:47:00 

    在asp.net2.0中的urlMappings倒是非常好用,可惜暂不支持正则表达式,不过,好在如果用IHttpModule的话

    不管什么样的请求都会先经过IHttpModule这样就为URL重写提供了一个好机会:

下面是我写的一个IHttpModule:
using System;
using System.Web;

public class ReWriteModule:IHttpModule
{
public ReWriteModule()
{
}
public override string ToString()
{
return this.GetType().ToString();
}


void IHttpModule.Dispose()
{

}
private static System.Xml.XmlDocument ruleDoc = null;
private static System.Xml.XmlDocument GetRuleConfig(System.Web.HttpContext app)
{
if (ruleDoc == null)
{
ruleDoc = new System.Xml.XmlDocument();
ruleDoc.Load(app.Server.MapPath("~/rule.xml"));
}
return ruleDoc;
}
public static string GetUrl(System.Web.HttpContext cxt,string path)
{

System.Xml.XmlDocument doc = GetRuleConfig(cxt);
System.Xml.XmlNodeList lst= doc.GetElementsByTagName("RewriterRule");
string pat="";
foreach (System.Xml.XmlNode nd in lst)
{
System.Xml.XmlNodeList sub = nd.ChildNodes[0].ChildNodes;
foreach(System.Xml.XmlNode chk in sub)
{
pat = "^" + chk.InnerText+"$";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pat, System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if(reg.IsMatch(path))
{
return reg.Replace(path, nd.ChildNodes[1].InnerText);
}
}
}
return null;

}
void IHttpModule.Init(HttpApplication context)
{
context.BeginRequest += delegate(object sender, EventArgs e)
{


System.Web.HttpContext cxt = context.Context;

if (cxt.Request.ContentType != "image/pjpeg")
{
string type = cxt.Request.ContentType.ToLower();
string path = cxt.Request.Path;
string apppath = cxt.Request.ApplicationPath;
path = path.Remove(0, apppath.Length);
path = "~" + path;

string newUrl = GetUrl(cxt, path.TrimEnd().TrimStart());
if (newUrl != null)
{
cxt.Response.Filter = new ResponseFilter(cxt.Response.Filter,cxt.Request.Path);
cxt.Response.Write("请求的路径:" + path);
cxt.Response.Write("<BR>");
cxt.Response.Write("转向的目的URL:" + newUrl);
cxt.Response.Write("<BR>");
cxt.RewritePath(newUrl);



}//如果要求处理所有的请求时用到
//else
//{
// cxt.Response.Write(cxt.Request.Path + "<BR>");
// cxt.Response.Write("你请求的资源不存在或无权访问!");
// cxt.Response.Flush();
// cxt.Response.End();
//}
}

};
}


}

  
 本文TagsC#  
 收藏本文  打印本文  论坛讨论  关闭窗口
· 上一篇:ASP.NET页面中标题单点解决方案
· 下一篇:谈谈HtmlControl与WebControl的区别与用途
· ASP.NET讲座(6)-ASP.NET的几种主要文件
· 在HTTP请求中添加特殊字符导致暴露JSP源代码文件
· 名称地址(Namespace)
· .NET Framework-Microsoft Visual Studio.NET 简介
· 优化Web数据库页面


关于本站 | 联系我们 | 业务合作 | 客户案例 | 诚聘英才 | 广告合作 | 收藏本站
海口动网先锋网络科技有限公司版权所有
Copyright © 2000 - 2006 Cndw.Com
中华人民共和国电信与信息服务业务经营许可证编号 琼 ICP 020077