How do you do a HTTP 301 permanant redirect route in ASP.NET MVC?
+2
A:
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);
Nick Craver
2010-02-07 13:34:01
The first line is not needed, as StatusCode will set the appropriate label too. Status is deprecated.
Jon Hanna
2010-08-22 11:19:16
+4
A:
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... http://stackoverflow.com/questions/1693548/correct-controller-code-for-a-301-redirect
JKG
2010-02-07 13:43:28
what if i am trying to redirect old .html files that no longer exist in the? can i use routing to handle these? What is the general approach?
Rich
2010-02-07 15:47:07
I'd probably go with some custom routes like this http://blog.eworldui.net/post/2008/04/ASPNET-MVC---Legacy-Url-Routing.aspx or i better yet using a http module with a separate config so you can easily phase out and in. http://www.hanselman.com/blog/ASPNETMVCAndTheNewIIS7RewriteModule.aspx
JKG
2010-02-07 16:52:27