【问题标题】:Returning "429 Too Many Requests" from action attribute从动作属性返回“429 Too Many Requests”
【发布时间】:2015-04-23 08:06:16
【问题描述】:

我正在编写一个类,我可以将它用作我的 ASP.NET Web API 操作的属性,它将根据用户的 IP 地址对用户进行速率限制。

类的逻辑运行良好,其基本结构如下:

public class ThrottleAttribute : ActionFilterAttribute
{

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        // Do various logic to determine if we should respond with a 429

        base.OnActionExecuting(actionContext);
    }
}

我通过在方法定义上方添加[Throttle] 注释在我的控制器操作中使用它。

OnActionExecuting 方法的某个地方,我想用429 HTTP 代码返回一个响应。从查看其他 SO 帖子(例如this one)看来,我可以通过以下方式做到这一点:

actionContext.Response = actionContext.Request.CreateResponse(
            HttpStatusCode.Conflict, 
            Message.Replace("{n}", Seconds.ToString())
        );

当我尝试使用此代码时,我收到以下错误:

“System.Net.Http.HttpRequestMessage”不包含“CreateResponse”的定义,并且找不到接受“System.Net.Http.HttpRequestMessage”类型的第一个参数的扩展方法“CreateResponse”(您是否缺少using 指令还是程序集引用?)

显然,CreateResponse 方法在 HttpRequestMessage 上不存在,但我不知道如何返回自定义响应以告诉用户他们已达到速率限制。我也试过这个:

actionContext.Response.StatusCode = HttpStatusCode.BadRequest;

但这也导致了对象引用未设置为对象实例的错误。

我如何从我的班级返回 429 Too Many Requests 响应,或者如果失败,只返回 Bad Request 响应?

【问题讨论】:

    标签: c# asp.net asp.net-web-api rate-limiting


    【解决方案1】:

    你可以抛出一个 HttpResponseException:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (TooManyRequests()) {
            throw new HttpResponseException((HttpStatusCode)429);
        }
        base.OnActionExecuting(filterContext);
    }
    

    您可以将 429 转换为 HttpStatusCode,即使该值不是枚举的一部分(来自 C# language specification 5.0)。

    【讨论】:

      【解决方案2】:

      尝试设置上下文的 HttpContext.Response 属性的 Response 以及设置 Result 属性。通过设置结果,它将不再强制调用后续过滤器。

      一个例子如下:

      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
          filterContext.HttpContext.Response.StatusCode = 429; // Too many requests
          filterContext.Result = new ContentResult
          {
              Content = "Too Many Requests"
          };
          base.OnActionExecuting(filterContext);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-14
        • 1970-01-01
        • 2021-12-13
        • 1970-01-01
        相关资源
        最近更新 更多