[英]How to set ActionExecutingContext status code
我正在使用本地化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);
}
}
您可以創建自定義操作結果以執行永久重定向:
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);
}
}
RedirectResult
有一個構造函數重載,它接受url和bool來指示重定向是否應該是永久性的:
filterContext.Result = new RedirectResult("/" + cookieLanguage, true);
從我所看到的,這應該在MVC 4中可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.