asp.net 2.0 中的URL重寫(xiě)以及urlMappings問(wèn)題
更新時(shí)間:2007年04月13日 00:00:00 作者:
在asp.net2.0中的urlMappings倒是非常好用,可惜暫不支持正則表達(dá)式,不過(guò),好在如果用IHttpModule的話(huà)
不管什么樣的請(qǐng)求都會(huì)先經(jīng)過(guò)IHttpModule這樣就為URL重寫(xiě)提供了一個(gè)好機(jī)會(huì):
下面是我寫(xiě)的一個(gè)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("請(qǐng)求的路徑:" + path);
cxt.Response.Write("<BR>");
cxt.Response.Write("轉(zhuǎn)向的目的URL:" + newUrl);
cxt.Response.Write("<BR>");
cxt.RewritePath(newUrl);
}//如果要求處理所有的請(qǐng)求時(shí)用到
//else
//{
// cxt.Response.Write(cxt.Request.Path + "<BR>");
// cxt.Response.Write("你請(qǐng)求的資源不存在或無(wú)權(quán)訪(fǎng)問(wèn)!");
// cxt.Response.Flush();
// cxt.Response.End();
//}
}
};
}
}
由于一旦進(jìn)行了URL重寫(xiě),原先的WEBFORM中的Action會(huì)發(fā)生改變,容易造成:請(qǐng)求的資源不存在問(wèn)題
具體怎么樣?各位DX看看就清楚了?。。?nbsp;
所有才有了這個(gè)ResponseFilter了,實(shí)現(xiàn)如下,
public class ResponseFilter:System.IO.Stream
{
public ResponseFilter(System.IO.Stream sink,string _str)
{
_sink = sink;
//
// TODO: 在此處添加構(gòu)造函數(shù)邏輯
//
this.str = _str;
}
private string str = "";
private System.IO.Stream _sink;
private long _position;
private System.Text.Encoding end=System.Text.Encoding.GetEncoding("GB18030");
private System.Text.StringBuilder oOutput = new System.Text.StringBuilder();
// The following members of Stream must be overriden.
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override long Length
{
get { return 0; }
}
public override long Position
{
get { return _position; }
set { _position = value; }
}
public override long Seek(long offset, System.IO.SeekOrigin direction)
{
return _sink.Seek(offset, direction);
}
public override void SetLength(long length)
{
_sink.SetLength(length);
}
public override void Close()
{
_sink.Close();
}
public override void Flush()
{
_sink.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _sink.Read(buffer, offset, count);
}
// The Write method actually does the filtering.
public override void Write(byte[] buffer, int offset, int count)
{
string szBuffer = System.Text.UTF8Encoding.UTF8.GetString(buffer, offset, count);
string ap="action=\"";
int pos=-1;
if ((pos=szBuffer.IndexOf(ap) )!= -1)
{
int epos = szBuffer.IndexOf("\"", pos + ap.Length+1);
if (epos != -1)
{
szBuffer= szBuffer.Remove(pos + ap.Length, epos - pos - ap.Length);
}
szBuffer = szBuffer.Insert(pos + ap.Length, this.str);
byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(szBuffer);
_sink.Write(data, 0, data.Length);
}
else
{
oOutput.Append(szBuffer);
}
//下面的這一段可以用來(lái)修改<Head></head>之間的內(nèi)容;
//Regex oEndFile = new Regex("</head>", RegexOptions.IgnoreCase|RegexOptions.Compiled);
//if (oEndFile.IsMatch(szBuffer))
//{
// //Append the last buffer of data
// //附加上緩沖區(qū)中的最后一部分?jǐn)?shù)據(jù)
// oOutput.Append(szBuffer);
// //Get back the complete response for the client
// //傳回完整的客戶(hù)端返回?cái)?shù)據(jù)
// string szCompleteBuffer = oOutput.ToString().ToLower();
// int ipos = szCompleteBuffer.IndexOf("<title>");
// int epos = szCompleteBuffer.IndexOf("</title>",ipos+7);
// string sp = szCompleteBuffer.Substring(ipos+7, epos - ipos );
// szCompleteBuffer = szCompleteBuffer.Remove(ipos+7,sp.Length-7);
// szCompleteBuffer = szCompleteBuffer.Insert(ipos + 7, "dhz");
// // szCompleteBuffer = szCompleteBuffer.Replace(sp, "dhz");
// //No match, so write out original data
// //沒(méi)有匹配,因此寫(xiě)入源代碼
// byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(szCompleteBuffer);
// _sink.Write(data, 0, data.Length);
//}
//else
//{
// oOutput.Append(szBuffer);
//}
}
}
//////而重候規(guī)則呢則是用xml文件配置如下;
當(dāng)然在web.config通過(guò)自定義配置節(jié)做也可以的
<?xml version="1.0" encoding="utf-8" ?>
<Rules>
<RewriterRule>
<LookFors>
<LookFor>~/(\d{4})/(\d{2})\.html</LookFor>
<LookFor>~/(\d{4})/(\d{2})/</LookFor>
<LookFor>~/(\d{4})/(\d{2})</LookFor>
<LookFor>~/(\d{4})/(\d{2})/index.html</LookFor>
</LookFors>
<SendTo>~/Pro.aspx?year=$1&month=$2</SendTo>
</RewriterRule>
<RewriterRule>
<LookFors>
<LookFor>~/pc</LookFor>
</LookFors>
<SendTo>~/Test2.aspx</SendTo>
</RewriterRule>
</Rules>
//這個(gè)規(guī)則寫(xiě)的不好,如第一個(gè)就可以用一個(gè)正則表達(dá)式來(lái)做。
不管什么樣的請(qǐng)求都會(huì)先經(jīng)過(guò)IHttpModule這樣就為URL重寫(xiě)提供了一個(gè)好機(jī)會(huì):
下面是我寫(xiě)的一個(gè)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("請(qǐng)求的路徑:" + path);
cxt.Response.Write("<BR>");
cxt.Response.Write("轉(zhuǎn)向的目的URL:" + newUrl);
cxt.Response.Write("<BR>");
cxt.RewritePath(newUrl);
}//如果要求處理所有的請(qǐng)求時(shí)用到
//else
//{
// cxt.Response.Write(cxt.Request.Path + "<BR>");
// cxt.Response.Write("你請(qǐng)求的資源不存在或無(wú)權(quán)訪(fǎng)問(wèn)!");
// cxt.Response.Flush();
// cxt.Response.End();
//}
}
};
}
}
由于一旦進(jìn)行了URL重寫(xiě),原先的WEBFORM中的Action會(huì)發(fā)生改變,容易造成:請(qǐng)求的資源不存在問(wèn)題
具體怎么樣?各位DX看看就清楚了?。。?nbsp;
所有才有了這個(gè)ResponseFilter了,實(shí)現(xiàn)如下,
public class ResponseFilter:System.IO.Stream
{
public ResponseFilter(System.IO.Stream sink,string _str)
{
_sink = sink;
//
// TODO: 在此處添加構(gòu)造函數(shù)邏輯
//
this.str = _str;
}
private string str = "";
private System.IO.Stream _sink;
private long _position;
private System.Text.Encoding end=System.Text.Encoding.GetEncoding("GB18030");
private System.Text.StringBuilder oOutput = new System.Text.StringBuilder();
// The following members of Stream must be overriden.
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override long Length
{
get { return 0; }
}
public override long Position
{
get { return _position; }
set { _position = value; }
}
public override long Seek(long offset, System.IO.SeekOrigin direction)
{
return _sink.Seek(offset, direction);
}
public override void SetLength(long length)
{
_sink.SetLength(length);
}
public override void Close()
{
_sink.Close();
}
public override void Flush()
{
_sink.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _sink.Read(buffer, offset, count);
}
// The Write method actually does the filtering.
public override void Write(byte[] buffer, int offset, int count)
{
string szBuffer = System.Text.UTF8Encoding.UTF8.GetString(buffer, offset, count);
string ap="action=\"";
int pos=-1;
if ((pos=szBuffer.IndexOf(ap) )!= -1)
{
int epos = szBuffer.IndexOf("\"", pos + ap.Length+1);
if (epos != -1)
{
szBuffer= szBuffer.Remove(pos + ap.Length, epos - pos - ap.Length);
}
szBuffer = szBuffer.Insert(pos + ap.Length, this.str);
byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(szBuffer);
_sink.Write(data, 0, data.Length);
}
else
{
oOutput.Append(szBuffer);
}
//下面的這一段可以用來(lái)修改<Head></head>之間的內(nèi)容;
//Regex oEndFile = new Regex("</head>", RegexOptions.IgnoreCase|RegexOptions.Compiled);
//if (oEndFile.IsMatch(szBuffer))
//{
// //Append the last buffer of data
// //附加上緩沖區(qū)中的最后一部分?jǐn)?shù)據(jù)
// oOutput.Append(szBuffer);
// //Get back the complete response for the client
// //傳回完整的客戶(hù)端返回?cái)?shù)據(jù)
// string szCompleteBuffer = oOutput.ToString().ToLower();
// int ipos = szCompleteBuffer.IndexOf("<title>");
// int epos = szCompleteBuffer.IndexOf("</title>",ipos+7);
// string sp = szCompleteBuffer.Substring(ipos+7, epos - ipos );
// szCompleteBuffer = szCompleteBuffer.Remove(ipos+7,sp.Length-7);
// szCompleteBuffer = szCompleteBuffer.Insert(ipos + 7, "dhz");
// // szCompleteBuffer = szCompleteBuffer.Replace(sp, "dhz");
// //No match, so write out original data
// //沒(méi)有匹配,因此寫(xiě)入源代碼
// byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(szCompleteBuffer);
// _sink.Write(data, 0, data.Length);
//}
//else
//{
// oOutput.Append(szBuffer);
//}
}
}
//////而重候規(guī)則呢則是用xml文件配置如下;
當(dāng)然在web.config通過(guò)自定義配置節(jié)做也可以的
<?xml version="1.0" encoding="utf-8" ?>
<Rules>
<RewriterRule>
<LookFors>
<LookFor>~/(\d{4})/(\d{2})\.html</LookFor>
<LookFor>~/(\d{4})/(\d{2})/</LookFor>
<LookFor>~/(\d{4})/(\d{2})</LookFor>
<LookFor>~/(\d{4})/(\d{2})/index.html</LookFor>
</LookFors>
<SendTo>~/Pro.aspx?year=$1&month=$2</SendTo>
</RewriterRule>
<RewriterRule>
<LookFors>
<LookFor>~/pc</LookFor>
</LookFors>
<SendTo>~/Test2.aspx</SendTo>
</RewriterRule>
</Rules>
//這個(gè)規(guī)則寫(xiě)的不好,如第一個(gè)就可以用一個(gè)正則表達(dá)式來(lái)做。
您可能感興趣的文章:
- asp.net不用設(shè)置iis實(shí)現(xiàn)url重寫(xiě) 類(lèi)似偽靜態(tài)路由
- ASP.NET中獲取URL重寫(xiě)前的原始地址詳解
- URL重寫(xiě)及干掉ASP.NET試圖狀態(tài)的實(shí)現(xiàn)方法
- asp.net URL重寫(xiě)簡(jiǎn)化版 速學(xué)URL重寫(xiě)
- 一個(gè)完整的ASP.NET 2.0 URL重寫(xiě)方案[翻譯]
- asp.net url重寫(xiě)淺談
- asp.net下實(shí)現(xiàn)URL重寫(xiě)技術(shù)的代碼
- asp.net下用url重寫(xiě)URLReWriter實(shí)現(xiàn)任意二級(jí)域名的方法
- Asp.Net URL重寫(xiě)的具體實(shí)現(xiàn)
相關(guān)文章
使用最小?WEB?API?實(shí)現(xiàn)文件上傳會(huì)遇到的坑
這篇文章主要介紹分享使用最小?WEB?API?實(shí)現(xiàn)文件上傳時(shí)會(huì)遇到的坑,在使用?.NET?6?的最小?WEB?API?來(lái)實(shí)現(xiàn)相同功能時(shí),總是會(huì)意外地遇到了不少坑,下面我們就來(lái)看看這些坑都是怎么處理的吧,需要的朋友可以參考下2022-02-02淺談.Net Core后端單元測(cè)試的實(shí)現(xiàn)
這篇文章主要介紹了淺談.Net Core后端單元測(cè)試的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03ASP.NET中實(shí)現(xiàn)定制自己的委托和事件參數(shù)類(lèi)
這篇文章主要介紹了ASP.NET中實(shí)現(xiàn)定制自己的委托和事件參數(shù)類(lèi),需要的朋友可以參考下2014-08-08Asp.Net 網(wǎng)站優(yōu)化系列之?dāng)?shù)據(jù)庫(kù)優(yōu)化 分字訣 分表(縱向拆分,橫向分區(qū))
上篇談了分庫(kù),這一篇我們來(lái)分表2010-06-06