Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set ActionExecutingContext status code

I am using localization actionfilterattribute and it is working perfectly fine, except I need it to redirect from / to /en with status code of 301 instead of 302. How can I fix this?

Code

public class Localize : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // .. irrelevent logic here ..

        // Set redirect code to 301
        filterContext.HttpContext.Response.Status = "301 Moved Permanently";
        filterContext.HttpContext.Response.StatusCode = 301;

        // Redirect
        filterContext.Result = new RedirectResult("/" + cookieLanguage);

        base.OnActionExecuting(filterContext);
    }
}

Proof

enter image description here

like image 208
Stan Avatar asked May 18 '13 21:05

Stan


2 Answers

You can create a custom action result to perform the permanent redirect:

public class PermanentRedirectResult : ActionResult
{
    public string Url { get; private set; }

    public PermanentRedirectResult(string url)
    {
        this.Url = url;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.StatusCode = 301;
        response.Status = "301 Moved Permanently";
        response.RedirectLocation = Url;
        response.End();
    }
}

that you could use to perform the redirect:

public class Localize : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // .. irrelevent logic here ..

        filterContext.Result = new PermanentRedirectResult("/" + cookieLanguage);
    }
}
like image 78
Darin Dimitrov Avatar answered Oct 03 '22 22:10

Darin Dimitrov


RedirectResult has a constructor overload that takes the url and a bool to indicate if the redirect should be permanent:

filterContext.Result = new RedirectResult("/" + cookieLanguage, true);

From what I can see, this should be available in MVC 4.

like image 40
Netricity Avatar answered Oct 03 '22 22:10

Netricity