How do you do a HTTP 301 permanant redirect route in ASP.NET MVC?
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With