Sta*_*tan 6 c# asp.net asp.net-mvc asp.net-mvc-4
我正在使用本地化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);
}
}
Run Code Online (Sandbox Code Playgroud)

您可以创建自定义操作结果以执行永久重定向:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以用来执行重定向:
public class Localize : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// .. irrelevent logic here ..
filterContext.Result = new PermanentRedirectResult("/" + cookieLanguage);
}
}
Run Code Online (Sandbox Code Playgroud)
RedirectResult 有一个构造函数重载,该重载使用url和bool来指示重定向是否应该是永久的:
filterContext.Result = new RedirectResult("/" + cookieLanguage, true);
Run Code Online (Sandbox Code Playgroud)
从我所看到的,这应该在MVC 4中可用。