PermanentRedirectResult – a 301 HTTP Redirect for ASP.net MVC
For a little project to learn ASP.net MVC, I needed my Controller to return a HTTP 301 Redirect. Unfortunately, just calling "return Redirect(url)" returns a HTTP 302 instead of a 301. After checking on the MVC Forums, there seems to be no "official" way to perform a 301 Redirect in a Controller. Of course, you can always modify the Response directly, but I decided that returning an ActionResult would be cleaner (and I think that makes it easier to unit test), even though it is essentially doing exactly that, setting a custom Status Code and Redirect Location.
So here is my little PermanentRedirectResult:
public class PermanentRedirectResult : ActionResult
{
public string Url { get; set; }
public PermanentRedirectResult(string url)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentException("url is null or empty", "url");
}
this.Url = url;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
context.HttpContext.Response.StatusCode = 301;
context.HttpContext.Response.RedirectLocation = Url;
}
}
[...] to Vote[FriendFeed] PermanentRedirectResult – a 301 HTTP Redirect for ASP.net MVC (8/6/2009)Thursday, August 06, 2009 from [...]
Microsoft introduces PermanentRedirect in ASP.NET 4.0 : http://weblogs.asp.net/vikram/archive/2009/05/22/permanent-redirect-in-asp-net-4-0.aspx
Sweet, I hope they add to to ASP.net MVC 2.0 as well.
[...] to return an ActionResult from the ControllerAction instead. As I happen to have already written a PermanentRedirectResult, my suggestion to improve this code is [...]
Thanks, just what I needed for my site