全局301从域重定向到www.domain

OrE*_*lse 6 vb.net asp.net global-asax http-status-code-301

我可以使用Global.asax的开始请求重定向一切,

mydomain.domainwww.mydomain.domain

如果这个是真的,我该怎么做?

Tom*_*son 11

对Jan的回答进行了一些细微的修改,这对我有用:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    string currentUrl = HttpContext.Current.Request.Url.ToString().ToLower(); 
    if (currentUrl.StartsWith("http://mydomain"))
    {
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", currentUrl.Replace("http://mydomain", "http://www.mydomain"));
        Response.End();
    }
}
Run Code Online (Sandbox Code Playgroud)

更改是使用BeginRequest事件并将currentUrl设置为HttpContext.Current.Request.Url而不是HttpContext.Current.Request.Path.看到:

http://www.mycsharpcorner.com/Post.aspx?postID=40


Jan*_*oom 5

protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
  string currentUrl = HttpContext.Current.Request.Path.ToLower();
  if(currentUrl.StartsWith("http://mydomain"))
  {
    Response.Status = "301 Moved Permanently";
    Response.AddHeader("Location", currentUrl.Replace("http://mydomain", "http://www.mydomain"));
    Response.End();
  }
}
Run Code Online (Sandbox Code Playgroud)

  • Request.Path仅返回虚拟路径,没有域名.上面的代码不起作用. (2认同)