要使用自定義模塊文件夾App_Code
創建文件CanonicalRedirectModule.cs
它與一個內容的網站應用程序的根文件夾:
using System;
using System.Web;
public class CanonicalRedirectModule : IHttpModule
{
public const string configKeyCanonicalHostName = "CanonicalHostName";
private string configCanonicalHostName;
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication context)
{
this.configCanonicalHostName = System.Configuration.ConfigurationManager.AppSettings[configKeyCanonicalHostName];
if (string.IsNullOrEmpty(this.configCanonicalHostName))
{
System.Diagnostics.Trace.TraceWarning("Can't find application setting {0} in configuration file (/configuration/appSettings/add/...).", configKeyCanonicalHostName);
//#if !DEBUG
// return;
//#endif
}
context.BeginRequest += new EventHandler(context_BeginRequest);
}
#endregion
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (app.Request.Url.Host != this.configCanonicalHostName) //&& !app.Request.IsLocal
{
UriBuilder newUrl = new UriBuilder(app.Request.Url);
newUrl.Host = this.configCanonicalHostName;
app.Response.Redirect(newUrl.ToString(), true);
}
}
}
然後在web.config
配置模塊:
<?xml version="1.0"?>
<system.web>
<!-- Configuration for classic pipeline mode -->
<httpModules>
<add name="CanonicalRedirectModule" type="CanonicalRedirectModule"/>
</httpModules>
</system.web>
<system.webServer>
<!-- Configuration for integrated pipeline mode -->
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" >
<add name="CanonicalRedirectModule" type="CanonicalRedirectModule"/>
</modules>
</system.webServer>
這對於其中一個網站非常有用!但是,它不適用於另一個。如果他們沒有安裝URL重寫模塊會怎麼樣? – Batfan 2010-11-09 20:48:23
嘗試協調重寫模塊的安裝 - 這是一般接受的擴展。另一方面,你可以編寫自己的模塊 - 這非常簡單(如果你需要支持,我可以爲你寫明天)。 – Matej 2010-11-09 22:15:22
這真的很友善,但我甚至不熟悉如何添加模塊/擴展。 – Batfan 2010-11-09 22:17:06