我使用下面的代码来限制我的 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/