利用URLRewriter重写实现伪二级域名
最近公司有个项目,要求将请求的参数放到放置到网址的前面
例:原请求网址:www.abc.com?jc=dfs 改写层 dfs.abc.com,实现这种伪的二级域名。着实下了一番功夫,今天我就在这总结下。
第一步:下载一个URLRewriter。
微软官方 关于URLRewriter的解释 http://www.microsoft.com/china/msdn/library/webservices/asp.net/URLRewriting.mspx
进入以后可以下载源代码,当然也可以去别的地方下载别人修改过的代码。要安装,安装完毕以后,在“我的文档”→“MSDN”→“URL Rewriting in ASP.NET” →“URLRewritingCode.sln”
第二步:要对URLRewriter里的方法重写
这里我们要重写的,就是URLRewriter程序集下的两个文件 “BaseModuleRewriter.cs”和“ModuleRewriter.cs”
1.BaseModuleRewriter.cs
[code=csharp]/// <summary>
/// Called when the module's AuthorizeRequest event fires.
/// </summary>
/// <remarks>This event handler calls the <see cref="Rewrite"/> method, passing in the
/// <b>RawUrl</b> and HttpApplication passed in via the <b>sender</b> parameter.</remarks>
protected virtual void BaseModuleRewriter_AuthorizeRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication) sender;
Rewrite(app.Request.Path, app);
}[/code]
改为[code=csharp]/// <summary>
/// Called when the module's AuthorizeRequest event fires.
/// </summary>
/// <remarks>This event handler calls the <see cref="Rewrite"/> method, passing in the
/// <b>RawUrl</b> and HttpApplication passed in via the <b>sender</b> parameter.</remarks>
protected virtual void BaseModuleRewriter_AuthorizeRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication) sender;
//Rewrite(app.Request.Path, app);
Rewrite(app.Request.Url.AbsoluteUri, app);
}
[/code]
2.ModuleRewriter.cs
[code=csharp]for(int i = 0; i < rules.Count; i++)
{
// get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules.LookFor) + "$";
// Create a regex (note that IgnoreCase is set...)
Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
// See if a match is found
if (re.IsMatch(requestedPath))
{
// match found - do any replacement needed
string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules.SendTo));
// log rewriting information to the Trace object
app.Context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl);
// Rewrite the URL
RewriterUtils.RewriteUrl(app.Context, sendToUrl);
break; // exit the for loop
}
}
[/code]
改为
for(int i = 0; i < rules.Count; i++)
{
// get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)