How to get status code from web client?

I am using the WebClient class to publish some data in a web form. I would like to receive a response code status form. So far I have learned how to get the status code if there is an exception

 Catch wex As WebException If TypeOf wex.Response Is HttpWebResponse Then msgbox(DirectCast(wex.Response, HttpWebResponse).StatusCode) End If 

However, if the form is submitted successfully and no exception is thrown, I will not know the status code (200, 301, 302, ...)

Is there a way to get the status code if there are no exceptions?

PS: I prefer not to use httpwebrequest / httpwebresponse

+79
c # webclient
Aug 26 '10 at 11:33
source share
10 answers

I tried it. ResponseHeaders do not include a status code.

If I'm not mistaken, WebClient is able to abstract several different requests in one method call (for example, correctly process 100 responses, redirects, etc.). I suspect that without using HttpWebRequest and HttpWebResponse separate status code may not be available.

It occurs to me that if you are not interested in intermediate status codes, you can safely assume that the final status code is in the 2xx range (successful), otherwise the call will not be successful.

The status code, unfortunately, is not in the ResponseHeaders dictionary.

+21
Aug 26 '10 at 11:43 on
source share

You can check if the error is of type WebException , and then check the response code;

 if (e.Error.GetType().Name == "WebException") { WebException we = (WebException)e.Error; HttpWebResponse response = (System.Net.HttpWebResponse)we.Response; if (response.StatusCode==HttpStatusCode.NotFound) System.Diagnostics.Debug.WriteLine("Not found!"); } 

or

 try { // send request } catch (WebException e) { // check e.Status as above etc.. } 
+77
Feb 09 '12 at 15:37
source share

There is a way to do this using reflection. It works with .NET 4.0. It accesses the private field and may not work in other versions of .NET without changes.

I have no idea why Microsoft did not disclose this property field.

 private static int GetStatusCode(WebClient client, out string statusDescription) { FieldInfo responseField = client.GetType().GetField("m_WebResponse", BindingFlags.Instance | BindingFlags.NonPublic); if (responseField != null) { HttpWebResponse response = responseField.GetValue(client) as HttpWebResponse; if (response != null) { statusDescription = response.StatusDescription; return (int)response.StatusCode; } } statusDescription = null; return 0; } 
+28
Jun 24 '11 at 15:56
source share

If you are using .Net 4.0 (or less):

 class BetterWebClient : WebClient { private WebRequest _Request = null; protected override WebRequest GetWebRequest(Uri address) { this._Request = base.GetWebRequest(address); if (this._Request is HttpWebRequest) { ((HttpWebRequest)this._Request).AllowAutoRedirect = false; } return this._Request; } public HttpStatusCode StatusCode() { HttpStatusCode result; if (this._Request == null) { throw (new InvalidOperationException("Unable to retrieve the status code, maybe you haven't made a request yet.")); } HttpWebResponse response = base.GetWebResponse(this._Request) as HttpWebResponse; if (response != null) { result = response.StatusCode; } else { throw (new InvalidOperationException("Unable to retrieve the status code, maybe you haven't made a request yet.")); } return result; } } 

If you are using .Net 4.5.X or later, switch to HttpClient :

 var response = await client.GetAsync("http://www.contoso.com/"); var statusCode = response.StatusCode; 
+27
Aug 31 '11 at 6:26 a.m.
source share

Eric's answer does not work on Windows Phone as it is. The following does:

 class WebClientEx : WebClient { private WebResponse m_Resp = null; protected override WebResponse GetWebResponse(WebRequest Req, IAsyncResult ar) { try { this.m_Resp = base.GetWebResponse(request); } catch (WebException ex) { if (this.m_Resp == null) this.m_Resp = ex.Response; } return this.m_Resp; } public HttpStatusCode StatusCode { get { if (m_Resp != null && m_Resp is HttpWebResponse) return (m_Resp as HttpWebResponse).StatusCode; else return HttpStatusCode.OK; } } } 

At least this happens when using OpenReadAsync ; rigorous testing is strongly recommended for other xxxAsync methods. The framework calls GetWebResponse somewhere along the code path; all you have to do is grab and cache the response object.

In this fragment, the backup code is 200, because the genuine HTTP errors are 500, 404, etc. - in any case are considered exceptions. The purpose of this trick is to capture error-free codes, in my specific case 304 (not changed). Thus, the fallback assumes that if the status code is somehow unavailable, at least it is not erroneous.

+8
Nov 13 '13 at 16:42
source share

You have to use

 if (e.Status == WebExceptionStatus.ProtocolError) { HttpWebResponse response = (HttpWebResponse)ex.Response; if (response.StatusCode == HttpStatusCode.NotFound) System.Diagnostics.Debug.WriteLine("Not found!"); } 
+3
Aug 21 2018-12-12T00
source share

Just in case, someone else needs the F # version of the hack described above.

 open System open System.IO open System.Net type WebClientEx() = inherit WebClient () [<DefaultValue>] val mutable m_Resp : WebResponse override x.GetWebResponse (req: WebRequest ) = x.m_Resp <- base.GetWebResponse(req) (req :?> HttpWebRequest).AllowAutoRedirect <- false; x.m_Resp override x.GetWebResponse (req: WebRequest , ar: IAsyncResult ) = x.m_Resp <- base.GetWebResponse(req, ar) (req :?> HttpWebRequest).AllowAutoRedirect <- false; x.m_Resp member x.StatusCode with get() : HttpStatusCode = if not (obj.ReferenceEquals (x.m_Resp, null)) && x.m_Resp.GetType() = typeof<HttpWebResponse> then (x.m_Resp :?> HttpWebResponse).StatusCode else HttpStatusCode.OK let wc = new WebClientEx() let st = wc.OpenRead("http://www.stackoverflow.com") let sr = new StreamReader(st) let res = sr.ReadToEnd() wc.StatusCode sr.Close() st.Close() 
+1
Nov 25 '15 at 18:13
source share

This is what I use to extend the functionality of WebClient. StatusCode and StatusDescription will always contain the most recent response code / description.

  /// <summary> /// An expanded web client that allows certificate auth and /// the retrieval of status' for successful requests /// </summary> public class WebClientCert : WebClient { private X509Certificate2 _cert; public WebClientCert(X509Certificate2 cert) : base() { _cert = cert; } protected override WebRequest GetWebRequest(Uri address) { HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address); if (_cert != null) { request.ClientCertificates.Add(_cert); } return request; } protected override WebResponse GetWebResponse(WebRequest request) { WebResponse response = null; response = base.GetWebResponse(request); HttpWebResponse baseResponse = response as HttpWebResponse; StatusCode = baseResponse.StatusCode; StatusDescription = baseResponse.StatusDescription; return response; } /// <summary> /// The most recent response statusCode /// </summary> public HttpStatusCode StatusCode { get; set; } /// <summary> /// The most recent response statusDescription /// </summary> public string StatusDescription { get; set; } } 

Thus, you can make a message and get the result through:

  byte[] response = null; using (WebClientCert client = new WebClientCert()) { response = client.UploadValues(postUri, PostFields); HttpStatusCode code = client.StatusCode; string description = client.StatusDescription; //Use this information } 
+1
03 Oct '16 at 22:03
source share

You can use the call "client.ResponseHeaders [..]", see the link for an example of returning material from the answer

-one
Aug 26 '10 at 11:44
source share

You can try this code to get the HTTP status code from WebException or from OpenReadCompletedEventArgs.Error. It also works in Silverlight because SL does not have a WebExceptionStatus.ProtocolError definition.

 HttpStatusCode GetHttpStatusCode(System.Exception err) { if (err is WebException) { WebException we = (WebException)err; if (we.Response is HttpWebResponse) { HttpWebResponse response = (HttpWebResponse)we.Response; return response.StatusCode; } } return 0; } 
-one
Dec 09 '14 at 9:54
source share



All Articles