且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用&QUOT重定向; WWW" URL的未经" WWW"网址或反之亦然?

更新时间:2022-12-09 11:14:47

我已经在过去的以下解决方案时,我没有去过能够修改IIS设置。

I've gone with the following solution in the past when I've not been able to modify IIS settings.

无论是在一个HttpModule(可能是干净的),或在的global.asax.cs或的Application_BeginRequest一些的BasePage类型的事件,比如我OnInit的执行针对所请求的URL检查,一个已知的字符串我想使用:

Either in an HTTPModule (probably cleanest), or global.asax.cs in Application_BeginRequest or in some BasePage type event, such as OnInit I perform a check against the requested url, with a known string I wish to be using:

public class SeoUrls : IHttpModule
{
  #region IHttpModule Members

  public void Init(HttpApplication context)
  {
      context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
  }

  public void Dispose()
  {
  }

  #endregion

  private void OnPreRequestHandlerExecute(object sender, EventArgs e)
  {
    HttpContext ctx = ((HttpApplication) sender).Context;
    IHttpHandler handler = ctx.Handler;

    // Only worry about redirecting pages at this point
    // static files might be coming from a different domain
    if (handler is Page)
    {
      if (Ctx.Request.Url.Host != WebConfigurationManager.AppSettings["FullHost"])
      {
        UriBuilder uri = new UriBuilder(ctx.Request.Url);

        uri.Host = WebConfigurationManager.AppSettings["FullHost"];

        // Perform a permanent redirect - I've generally implemented this as an 
        // extension method so I can use Response.PermanentRedirect(uri)
        // but expanded here for obviousness:
        response.AddHeader("Location", uri);
        response.StatusCode = 301;
        response.StatusDescription = "Moved Permanently";
        response.End();
      }
    }
  }
}

然后在你的web.config中注册类:

Then register the class in your web.config:

<httpModules>
  [...]
  <add type="[Namespace.]SeoUrls, [AssemblyName], [Version=x.x.x.x, Culture=neutral, PublicKeyToken=933d439bb833333a]" name="SeoUrls"/>
</httpModules>

此方法效果相当好适合我们。

This method works quite well for us.