System.Net.WebException HTTP status code
Asked Answered
W

6

174

Is there an easy way to get the HTTP status code from a System.Net.WebException?

Wystand answered 31/8, 2010 at 23:49 Comment(0)
P
278

Maybe something like this...

try
{
    // ...
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        var response = ex.Response as HttpWebResponse;
        if (response != null)
        {
            Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
        }
        else
        {
            // no http status code available
        }
    }
    else
    {
        // no http status code available
    }
}
Puebla answered 1/9, 2010 at 0:4 Comment(7)
but in case of "connectfailure" exception of webexception i get response as null, in that case how can i get the httpstatus codeAphis
@rusty: You can't. If there's a connection failure then there is no HTTP status code to be got.Puebla
If the error is a ProtocolError, you don't have to check the response for null. See the comment in the example on this MSDN pageFafnir
@AndrasToth But tools like ReSharper will give you a warning if you omit the null-check. And in any case, it's good practise to code defensively.Cad
@TomLint I don't think it's about warnings or defensive coding, it's that @Puebla is using the as operator, which is a dynamic cast, so the check for null is to see if the cast has worked or not, at runtime.Guth
@Guth I know, but there are people who just assume the cast just works. And oftentimes it does, depending on the situation. The null-check gives you ensurance that your assumption was actually correct, and prevents unexpected exceptions should the cast fail.Cad
How get HTTP Substatus value ? For example, 404.13 Content Length Too Large Reference: learn.microsoft.com/en-us/iis/configuration/system.webServer/…Recessive
H
32

By using the null-conditional operator (?.) you can get the HTTP status code with a single line of code:

 HttpStatusCode? status = (ex.Response as HttpWebResponse)?.StatusCode;

The variable status will contain the HttpStatusCode. When the there is a more general failure like a network error where no HTTP status code is ever sent then status will be null. In that case you can inspect ex.Status to get the WebExceptionStatus.

If you just want a descriptive string to log in case of a failure you can use the null-coalescing operator (??) to get the relevant error:

string status = (ex.Response as HttpWebResponse)?.StatusCode.ToString()
    ?? ex.Status.ToString();

If the exception is thrown as a result of a 404 HTTP status code the string will contain "NotFound". On the other hand, if the server is offline the string will contain "ConnectFailure" and so on.

(And for anybody that wants to know how to get the HTTP substatus code. That is not possible. It is a Microsoft IIS concept that is only logged on the server and never sent to the client.)

Hawkie answered 17/1, 2017 at 13:31 Comment(2)
Not sure whether the ?. operator was originally named null propagation operator or null-conditional operator during preview release. But Atlassian resharper gives a warning to use null propagation operator in such scenarios. Nice to know that it is also called null-conditional operator.Efficacious
A bit late to this party, but fair warning that the null-conditional operator is a C# 6.0 feature, so one needs to be using a compiler that supports it. Stack Overflow answer with further details. VS 2015+ has it by default, but if one is using any kind of build/deploy environment other than just "their machine", other things might need to be taken into consideration.Mishamishaan
G
18

(I do realise the question is old, but it's among the top hits on Google.)

A common situation where you want to know the response code is in exception handling. As of C# 7, you can use pattern matching to actually only enter the catch clause if the exception matches your predicate:

catch (WebException ex) when (ex.Response is HttpWebResponse response)
{
     doSomething(response.StatusCode)
}

This can easily be extended to further levels, such as in this case where the WebException was actually the inner exception of another (and we're only interested in 404):

catch (StorageException ex) when (ex.InnerException is WebException wex && wex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.NotFound)

Finally: note how there's no need to re-throw the exception in the catch clause when it doesn't match your criteria, since we don't enter the clause in the first place with the above solution.

Garvin answered 18/10, 2017 at 12:55 Comment(0)
B
11

this works only if WebResponse is a HttpWebResponse.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}
Bicameral answered 16/1, 2014 at 10:26 Comment(2)
why only deal with 401-Unauthorized instead of all possible HTTP error status codes? this is the worst answerGuth
@Guth This is just an example. Any reasonable developer understands this. Your comment is the most thoughtless I've ever read here.Bicameral
A
6

You can try this code to get HTTP status code from WebException. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

HttpStatusCode GetHttpStatusCode(WebException we)
{
    if (we.Response is HttpWebResponse)
    {
        HttpWebResponse response = (HttpWebResponse)we.Response;
        return response.StatusCode;
    }
    return null;
}
Adowa answered 9/12, 2014 at 10:5 Comment(3)
return 0 ? or better HttpStatusCode? (nullable)?Recessive
Will this work? var code = GetHttpStatusCode(ex); if (code != HttpStatusCode.InternalServerError) {EventLog.WriteEntry( EventLog.WriteEntry("MyApp", code, System.Diagnostics.EventLogEntryType.Information, 1);}Unto
I can't understand what you wanted to do in this sample. In what cases you wanted event to be logged?Adowa
A
1

I'm not sure if there is but if there was such a property it wouldn't be considered reliable. A WebException can be fired for reasons other than HTTP error codes including simple networking errors. Those have no such matching http error code.

Can you give us a bit more info on what you're trying to accomplish with that code. There may be a better way to get the information you need.

Ambidexter answered 31/8, 2010 at 23:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.