我正在使用本地化actionfilterattribute,它工作得很好,除了我需要它从/
重定向到/en
,状态代码为301
而不是302
。我该如何解决这个问题?
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);
}
}
答案 0 :(得分:7)
您可以创建自定义操作结果以执行永久重定向:
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();
}
}
您可以用来执行重定向:
public class Localize : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// .. irrelevent logic here ..
filterContext.Result = new PermanentRedirectResult("/" + cookieLanguage);
}
}
答案 1 :(得分:5)
RedirectResult
有一个构造函数重载,它接受url和bool来指示重定向是否应该是永久性的:
filterContext.Result = new RedirectResult("/" + cookieLanguage, true);
从我所看到的情况来看,这应该可以在MVC 4中找到。