6

我正在使用本地化 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);
    }
}

证明

在此处输入图像描述

4

2 回答 2

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);
    }
}
于 2013-05-18T21:20:42.840 回答
5

RedirectResult有一个构造函数重载,它接受 url 和一个 bool 来指示重定向是否应该是永久的:

filterContext.Result = new RedirectResult("/" + cookieLanguage, true);

据我所知,这应该在 MVC 4 中可用。

于 2013-05-18T21:25:13.547 回答