

RFC 8164 HTTP/2: Opportunistic Security for HTTP/2 (2017).RFC 7541 HTTP/2: HPACK Header Compression (2015).RFC 7230 HTTP/1.1: Message Syntax and Routing (2014).Still, sometimes the client needs to inspect other HTTP server responses as well.
#Webrequest vs httpclient code#
Web services should usually throw exceptions from web method code so that they are returned to the client inside the SOAP response. EnsureSuccessStatusCode will throw the same exception as GetStringAsync in the first sample code. StatusCode and ReasonPhrase properties of response can be used to get the corresponding response values. In this case content will contain page content for both non-error and error responses. Var response = await httpClient.GetAsync(uri) To retrieve the body of error responses, the client code needs to be modified: var httpClient = new HttpClient() both the status code and the reason phrase. Var result = await httpClient.GetStringAsync(uri) įor error status codes httpClient.GetStringAsync will throw a HttpRequestException with Message property containing Response status code does not indicate success: 500 (Database not available)., i.e. Using HttpClient this would be typical client code: var httpClient = new HttpClient() Reason phrase can't be accessed in this case. Message property will contain a generic status dependent error message ( The remote server returned an error: (500) Internal Server Error.), while Response.GetResponseStream() returns a stream with the page content ( Database not available in my case). Using ( var reader = new StreamReader(e.Response.GetResponseStream())) Using ( var reader = new StreamReader(response.GetResponseStream()))įor error status codes response.GetResponseStream will throw a WebException which can be inspected as follows: catch (WebException e) Using HttpWebRequest the typical client code would look like: var request = WebRequest.Create(uri) This will result in the following response: HTTP/1.1 500 Database not available Throw new HttpResponseException (response) Response.Content = new StringContent( "Database not available")

Response.ReasonPhrase = "Database not available" Var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) On the server side I'll use Web API to return the desired response: public class TestController : ApiController Let's take a more detailed look at different scenarios, starting with two generic client classes: HttpWebRequestand the newer HttpClient. Unfortunately, based on the API used, it's again not always possible to retrieve the page content from code.

The protocol allows two different approaches in such cases: Sometimes it can be beneficial to include additional information about the error that occurred. HTTP protocol defines status codes as the means of informing the client about different error conditions on the server during the request processing.
