ASP.NET Response.Redirect uses 302 instead of 301

前端 未结 4 1414
不知归路
不知归路 2020-12-28 14:00

using the following code

context.Response.StatusCode = 301;

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

I can see in

4条回答
  •  隐瞒了意图╮
    2020-12-28 14:15

    I am combining the answers above with something I use if I have old domains/sub-domains for different versions of a site that I want to redirect to the current, mostly for SEO reasons, so as to not have multiple versions of the same site at different URLs:

    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;
            }
          }
        }
      }
    }
    

提交回复
热议问题