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;
}
}