ASP.NET Response.Redirect使用302而不是301

ASP.NET Response.Redirect uses 302 instead of 301

使用以下代码

1
2
3
4
context.Response.StatusCode = 301;

context.Response.Redirect(newUrl, true);
context.Response.End();

我可以在提琴手中看到它使用的是302而不是301。我应该在重定向调用之后设置状态吗?


如果使用的是ASP.Net 4.0,则可以使用Response.RedirectPermanent,它将使用301而不是302。


Response.Redirect()将用重定向代码覆盖StatusCode属性(302)。另外,由于您正在使用带有布尔参数的Response.Redirect()重载,因此,如果您要自己调用Response.End(),则应将其设置为False。否则,它是多余的,并且可能导致错误。

尝试以下操作(ASP.NET 4.0之前的版本; Adam Butler的答案涵盖了新的最佳实践):

1
2
3
context.Response.Redirect(newUrl, false);
context.Response.StatusCode = 301;
context.Response.End();


301是可缓存的。如果使用的是ASP.NET 4.0,则可以使用RedirectPermanent。

此外,在重定向后设置您的状态代码

也请调查以下答案。 Response.Redirect HTTP状态码


如果我想将旧版本的站点的旧域/子域重定向到当前版本(主要是出于SEO的原因),以便没有多个版本的站点,则我将上面的答案与我使用的内容结合在一起同一站点的不同URL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Net;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace myapp.web {
  public class Global : HttpApplication {
    void Application_Start(object sender, EventArgs e) {
      // Code that runs on application startup
      AreaRegistration.RegisterAllAreas();
      GlobalConfiguration.Configure(WebApiConfig.Register);
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
      BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

    protected void Application_BeginRequest(object sender, EventArgs e) {
      //some of these checks may be overkill
      if ((HttpContext.Current != null)
        && (HttpContext.Current.Request != null)
        && (HttpContext.Current.Request.ServerVariables != null)
        && (!String.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_HOST"]))
        ) {
        switch (HttpContext.Current.Request.ServerVariables["HTTP_HOST"]) {
          case"old.url.com":
            HttpContext.Current.Response.RedirectPermanent("https://new.url.com", true);
            //status code is not needed if redirect perm is used
            HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.MovedPermanently;
            HttpContext.Current.Response.End();
            break;
          case"nightly.old.url.com":
            HttpContext.Current.Response.RedirectPermanent("https://nightly.new.url.com", true);
            //status code is not needed if redirect perm is used
            HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.MovedPermanently;
            HttpContext.Current.Response.End();
            break;
        }
      }
    }
  }
}