A way to return a permanent 301 redirect result in ASP.NET MVC - RedirectResult returns a temporary 302 redirect

I recommend

ASP.NET MVC 2.0 supplies a RedirectResult which returns a HTTP 302 temporary redirect. In many cases you really want a HTTP 301 permanent redirect result.

The following class will do the job:

using System.Web.Mvc;

/// 
/// Redirects using a 301 permanent redirect HTTP status code.
/// 
public class PermanentRedirectResult : RedirectResult
{
   public PermanentRedirectResult(string url) : base(url)
   {
   }

   public override void ExecuteResult(ControllerContext context)
   {
      base.ExecuteResult(context);
      context.HttpContext.Response.StatusCode = 301;
   }
}
I included this class in the TTC Tools which you can find on github.

It can be used in the same manner as RedirectResult.

Technical ASP.NET MVC September 23, 2010


Comments