I am trying to get the HTTP status code number from the HttpWebResponse
object returned from a HttpWebRequest
. I was hoping to get the actual numbers (200, 301,302, 404, etc.) rather than the text description. ("Ok", "MovedPermanently", etc.) Is the number buried in a property somewhere in the response object? Any ideas other than creating a big switch function? Thanks.
HttpWebRequest webRequest = (HttpWebRequest)WebRequest .Create("http://www.gooogle.com/"); webRequest.AllowAutoRedirect = false; HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); //Returns "MovedPermanently", not 301 which is what I want. Console.Write(response.StatusCode.ToString());
The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET : The resource has been fetched and is transmitted in the message body.
Just use Chrome browser. Hit F12 to get developer tools and look at the network tab. Shows you all status codes, whether page was from cache etc.
This class contains support for HTTP-specific uses of the properties and methods of the WebResponse class. The HttpWebResponse class is used to build HTTP stand-alone client applications that send HTTP requests and receive HTTP responses.
The HTTP Status Code 207 means that the message body that follows is by default an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.
Console.Write((int)response.StatusCode);
HttpStatusCode (the type of response.StatusCode
) is an enumeration where the values of the members match the HTTP status codes, e.g.
public enum HttpStatusCode { ... Moved = 301, OK = 200, Redirect = 302, ... }
You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:
try { wResp = (HttpWebResponse)wReq.GetResponse(); wRespStatusCode = wResp.StatusCode; } catch (WebException we) { wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With