How do I get StatusCode from HttpRequestException?

不问归期 提交于 2019-11-29 00:48:56
Lex Li

Status code was passed as part of a string to HttpRequestException so that you cannot recover it from such exceptions alone.

The design of System.Net.Http requires you to access HttpResponseMessage.StatusCode instead of waiting for the exception.

http://msdn.microsoft.com/en-us/library/system.net.http.httpresponsemessage(v=vs.110).aspx

If you are now following the Microsoft guide, make sure you understand clearly why it asks you to call HttpResponseMessage.EnsureSucessStatusCode. If you don't call that function, there should be no exception.

Steve

For what its worth, this guy did something clever: https://social.msdn.microsoft.com/Forums/vstudio/en-US/dc9bc426-1654-4319-a7fb-383f00b68def/c-httpresponsemessage-throws-exception-httprequestexception-webexception-the-remote-name?forum=csharpgeneral

In the case where I needed an exception status property, I can do this:

catch (HttpRequestException requestException)
{
    if (requestException.InnerException is WebException webException && webException.Status == WebExceptionStatus.NameResolutionFailure)
    {
        return true;
    }

    return false;
}
Surender Singh Malik

As mentioned by others as well it's not a good practice to get the StatusCode from HttpRequestException, the same can be done beforehand with HttpResponseMessage.StatusCode after checking HttpResponseMessage.IsSuccessStatusCode

Anyhow if due to some constraint/requirement one has to read StatusCode, There can be two solution

  1. Extended the HttpResponseMessage with your custom exception explained here
  2. Hack on the HttpRequestException.ToString to get the StatusCode, As the message is a constant post fixed by StatusCode and Repharse.

Below is the code in System.Net.Http.HttpResponseMessage Where SR.net_http_message_not_success_statuscode ="Response status code does not indicate success: {0} ({1})."

public HttpResponseMessage EnsureSuccessStatusCode()
    {
        if (!this.IsSuccessStatusCode)
        {
            if (this.content != null)
            {
                this.content.Dispose();
            }
            throw new HttpRequestException(string.Format(CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, new object[]
            {
                (int)this.statusCode,
                this.ReasonPhrase
            }));
        }
        return this;
    }

This has worked for me

var response = ex.Response;
var property = response.GetType().GetProperty("StatusCode");
if ( property != null && (HttpStatusCode)property.GetValue(response) == HttpStatusCode.InternalServerError)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!