This one stumped me for an embarrassingly long time. I have several pages that I am in the process of moving permanently to a new domain. The site is written using ASP.NET MVC and I wanted my controller to return a 301 Moved Permanently status (along with the location header) if the page in question has been moved.
Originally I was just trying to set the status and header manually. Not a good idea, and ASP.NET MVC makes it difficult. That was my first clue I was not heading in the right direction. My next thought was to create and return a new class
HttpMovedResult derived from
This worked, and was remarkably simple and easy to use.
But it still felt wrong â€“ returning a specific status code was easy but I couldnâ€™t set the required Location header. Try as I might though, I couldnâ€™t find a class that would return a redirect status and the Location header for me.
Of course, I was so focused on classes, I neglected the controller methods. Sure enough, the
Controller class has several methods for dealing with redirects, including
RedirectPermanent(url), which will return a 301 Moved Permanently status code, along with the appropriate Location header. If you just need a temporary redirect,
Redirect(url) will do the same thing with a 302 Found status code.