8

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

splattne
  • 102,760
  • 52
  • 202
  • 249
Rich
  • 93
  • 1
  • 3

2 Answers2

8

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

Community
  • 1
  • 1
JKG
  • 4,369
  • 2
  • 17
  • 10
  • 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 Feb 07 '10 at 15:47
  • 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 Feb 07 '10 at 16:52
  • 1
    There's already RedirectPermanent in mvc. Take a look at http://stackoverflow.com/a/16980631/532517 – H.Wolper Dec 03 '15 at 12:56
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);
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 3
    The first line is not needed, as StatusCode will set the appropriate label too. Status is deprecated. – Jon Hanna Aug 22 '10 at 11:19