Is there an easy way to get the HTTP status code from a System.Net.WebException
?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
By using the null-conditional operator (
?.
) you can get the HTTP status code with a single line of code:The variable
status
will contain theHttpStatusCode
. When the there is a more general failure like a network error where no HTTP status code is ever sent thenstatus
will be null. In that case you can inspectex.Status
to get theWebExceptionStatus
.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: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.
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.
this works only if WebResponse is a HttpWebResponse.
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.
Maybe something like this...
(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:
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 in404
):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.