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?
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);
}
}
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With