在 HttpResponseMessage 中检测 429 和 418 return 代码

Detecting 429 and 418 return codes in HttpResponseMessage

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

HTTP Return 代码

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和418return码对我来说尤为重要

我正在这样使用 WebApi:


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");
    }
}

但我对如何检测有问题的 return 代码感到困惑,因为它们没有在 HttpStatusCode 中定义。先不说如何判断状态码是在4XX还是5XX范围内。

我正在使用 dotnetcore3.1,这很重要,因为我不能仅通过调用 httpResponse.EnsureSuccessStatusCode() 并从异常中提取它来获取状态代码。

可以将任意整数值分配给 enum 类型,因此在 switch 中使用它就像 cast

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

}

From the specs

Enum values and operations

Each enum type defines a distinct type; an explicit enumeration conversion (Explicit enumeration conversions) is required to convert between an enum type and an integral type, or between two enum types. The set of values that an enum type can take on is not limited by its enum members. In particular, any value of the underlying type of an enum can be cast to the enum type, and is a distinct valid value of that enum type.

或按照 @Dominik further information at Enum Type Conversions

的建议