gpt4 book ai didi

asp.net - 从 ActionFilterAttribute 返回自定义 HTTP 代码

转载 作者:行者123 更新时间:2023-12-03 22:00:31 25 4
gpt4 key购买 nike

我使用下面的代码来限制我的 ASP.NET Web Api:

public class Throttle : ActionFilterAttribute
{
public override async Task OnActionExecutingAsync(HttpActionContext context, CancellationToken cancellationToken)
{
// ...
if (throttle)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Conflict));
}
}
}

但是,我无法返回错误代码 429,因为它不在 HttpStatusCode 枚举中。有没有办法返回自定义错误代码?

最佳答案

我在 here 上找到了这个.

var response = new HttpResponseMessage
{
StatusCode = (HttpStatusCode)429,
ReasonPhrase = "Too Many Requests",
Content = new StringContent(string.Format(CultureInfo.InvariantCulture, "Rate limit reached. Reset in {0} seconds.", data.ResetSeconds))
};

response.Headers.Add("Retry-After", data.ResetSeconds.ToString(CultureInfo.InvariantCulture));
actionContext.Response = response;

希望这可以帮助

关于asp.net - 从 ActionFilterAttribute 返回自定义 HTTP 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25324851/

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