分享
三行代码  ›  专栏  ›  技术社区  ›  Benj

检测HttpResponseMessage中的429和418返回码

  •  0
  • Benj  · 技术社区  · 1 周前

    我正在使用WebAPI。下的规范 https://binance-docs.github.io/apidocs/spot/en/#general-api-information 定义Http响应代码的以下规则:

    HTTP 4XX return codes are used for malformed requests; the issue is on the sender's side.
    
    HTTP 403 return code is used when the WAF Limit (Web Application Firewall) has been violated.
    
    HTTP 429 return code is used when breaking a request rate limit.
    
    HTTP 418 return code is used when an IP has been auto-banned for continuing to send requests after receiving 429 codes.
    
    HTTP 5XX return codes are used for internal errors; the issue is on Binance's side.
    
    With using /wapi/v3 [something fancy]
    

    所以检测429和418返回码对我来说尤为重要。

    
    httpResponse = await _httpClient.SendAsync(httpRequest, cancellationToken)
        .ConfigureAwait(false);
    
    if (httpResponse.IsSuccessStatusCode)
    {
        return JsonSerializer.Deserialize<TResponse>(
            await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
    }
    else
    {
        switch (httpResponse.StatusCode)
        {
            case (HttpStatusCode.Forbidden):
                throw new BinanceWafLimitViolation();
    
            // ... More Status Codes here ...
    
            default:
                throw new RestApiException("Http status code indicates failure");
        }
    }
    

    但是我对如何检测有问题的返回码感到困惑,因为它们没有在中定义 HttpStatusCode

    我使用的是dotnetcore3.1,这很重要,因为我不能通过调用 httpResponse.EnsureSuccessStatusCode()

    1 回复  |  直到 1 周前
        1
  •  4
  •   00110001    1 周前

    可以将任意整数值赋给 enum swtich 铸造

    switch (httpResponse.StatusCode)
    {
       case HttpStatusCode.Forbidden:
        ...
       case HttpStatusCode.TooManyRequests:
        ...
       case (HttpStatusCode)418:
        ...
    
    }
    

    From the specs

    枚举值和操作

    转换需要转换(显式枚举转换) 在枚举类型和整数类型之间,或在两个枚举类型之间。 枚举可以强制转换为枚举类型,并且是 枚举类型

    或者按照 @Dominik Enum Type Conversions