gpt4 book ai didi

c# - 如何设置 ActionExecutingContext 状态码

转载 作者:太空狗 更新时间:2023-10-29 21:05:03 32 4
gpt4 key购买 nike

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

最佳答案

您可以创建自定义操作结果来执行永久重定向:

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);
}
}

关于c# - 如何设置 ActionExecutingContext 状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16629029/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com