本文介绍了HttpWebResponse状态码429的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用API​​进行一些集成工作,当您达到每日限额时,该API返回HttpStatusCode 429.但是,Web响应对象中的Enum HttpStatusCode不包含此代码.

I'm doing some integration work with an API which returns a HttpStatusCode 429 when you've hit your daily limit. However the Enum HttpStatusCode in the web response object does not contain this code.

有人可以让我知道如何检查此响应代码吗?

Can some one let me know how I can check for this response code?

以下是一些代码来显示我要完成的工作:

Here is some code to show what I'm trying to accomplish:

try
{
  //do something
}
catch (WebException webExp)
{
     var response = (HttpWebResponse) webExp.Response;

     //here I want to check status code for too many requests but it is not   in the enum.
    if (response.StatusCode == HttpStatusCode.TooManyRequests) throw webExp;
}

推荐答案

我遇到了同样的问题,在寻找解决方案时我意识到了一些事情.

I have the same problem and I realise a few things while I search for a solution.

  • WebExceptionStatus enum不等同于您调用的API返回的http状态代码.相反,它是一个可能的错误枚举,可能在http调用期间发生.
  • 当您从API收到错误(400到599)时将返回的WebExceptionStatus错误代码是WebExceptionStatus.ProtocolError aka 7(即int).
  • 当您需要获取响应正文或从api返回的真实http状态代码时,首先需要检查WebExceptionStatus.Status是否为WebExceptionStatus.ProtocolError.然后,您可以从WebExceptionStatus.Response获取真实的响应并读取其内容.
  • WebExceptionStatus enum is not equivalent to http status code that the API you call returned. Instead it is a enum of possible error that may occour during a http call.
  • The WebExceptionStatus error code that will be returned when you receive an error (400 to 599) from your API is WebExceptionStatus.ProtocolError aka number 7 as int.
  • When you need to get the response body or the real http status code returned from the api, first you need to check if WebExceptionStatus.Status is WebExceptionStatus.ProtocolError. Then you can get the real response from WebExceptionStatus.Response and read its content.

这是一个示例:

try
{
    ...
}
catch (WebException webException)
{
    if (webException.Status == WebExceptionStatus.ProtocolError)
    {
        var httpResponse = (HttpWebResponse)webException.Response;
        var responseText = "";
        using (var content = new StreamReader(httpResponse.GetResponseStream()))
        {
            responseText = content.ReadToEnd(); // Get response body as text
        }
        int statusCode = (int)httpResponse.StatusCode; // Get the status code (429 error code will be here)
        return statusCode;
    }

    // Handle other webException.Status errors
}

这篇关于HttpWebResponse状态码429的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 09:02