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

标签 asp.net asp.net-web-api asp.net-web-api2

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

相关文章:

c# - MultipartFormDataStreamProvider 和上传后立即读取文件有时会失败

angularjs - 带有空参数的 $http.get 没有命中 Web API Controller

c# - 如何将默认 Web API 2 更改为 JSON 格式化程序?

javascript - 在 ASP.NET 网站上将 javascript 放在结束正文标记之前可以吗?

asp.net - 将文本放在一个小按钮中

asp.net - 垂直滚动时卡住 gridview 寻呼机

css - 如果肢体语言发生变化,我们可以固定页面方向吗?

asp.net-mvc-4 - ASP.NET MVC 4 Web API 方法调用元数据

.net - 使用 Microsoft bot 框架下载文件(pdf/图像)

c# - 目标机主动拒绝导致无法连接?