How do you do a 301 permanant redirect route in AS

2019-06-16 15:35发布

问题:

How do you do a HTTP 301 permanant redirect route in ASP.NET MVC?

回答1:

Create a class that inherits from ActionResult...


    public class PermanentRedirectResult : ActionResult
    {    
        public string Url { get; set; }

        public PermanentRedirectResult(string url)
        {
            this.Url = url;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.MovedPermanently;
            context.HttpContext.Response.RedirectLocation = this.Url;
            context.HttpContext.Response.End();
        }
    }

Then to use it...


        public ActionResult Action1()
        {          
            return new PermanentRedirectResult("http://stackoverflow.com");
        }



A more complete answer that will redirect to routes... Correct Controller code for a 301 Redirect



回答2:

You want a 301 redirect, a 302 is temporary, a 301 is permanent. In this example,context is the HttpContext:

context.Response.Status = "301 Moved Permanently";
context.Response.StatusCode = 301;
context.Response.AppendHeader("Location", nawPathPathGoesHere);