Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do a 301 permanant redirect route in ASP.Net MVC

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

like image 962
Rich Avatar asked Feb 07 '10 13:02

Rich


2 Answers

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

like image 148
JKG Avatar answered Oct 13 '22 02:10

JKG


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);
like image 38
Nick Craver Avatar answered Oct 13 '22 04:10

Nick Craver