You might consider a different approach:
protected void Application_BeginRequest (object sender, EventArgs e)
{
if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
{
UriBuilder builder = new UriBuilder (Request.Url);
builder.Host = "www." + Request.Url.Host;
Response.Redirect (builder.ToString (), true);
}
}
This will however do a 302 redirect so a little tweak is recommended:
protected void Application_BeginRequest (object sender, EventArgs e)
{
if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
{
UriBuilder builder = new UriBuilder (Request.Url);
builder.Host = "www." + Request.Url.Host;
Response.StatusCode = 301;
Response.AddHeader ("Location", builder.ToString ());
Response.End ();
}
}
This one will return 301 Moved Permanently.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…