如何设置ActionExecutingContext状态代码

时间:2013-05-18 21:16:15

标签: 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);
    }
}

证明

enter image description here

2 个答案:

答案 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中找到。