System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode C# (CSharp) Method

EnsureSuccessStatusCode() public method

public EnsureSuccessStatusCode ( ) : HttpResponseMessage
return HttpResponseMessage
        public HttpResponseMessage EnsureSuccessStatusCode()
        {
            if (!IsSuccessStatusCode)
            {
                // Disposing the content should help users: If users call EnsureSuccessStatusCode(), an exception is
                // thrown if the response status code is != 2xx. I.e. the behavior is similar to a failed request (e.g.
                // connection failure). Users don't expect to dispose the content in this case: If an exception is 
                // thrown, the object is responsible fore cleaning up its state.
                if (_content != null)
                {
                    _content.Dispose();
                }

                throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, (int)_statusCode,
                    ReasonPhrase));
            }
            return this;
        }

Usage Example

Example #1
1
        private async Task<string> PostRequest(string URL)
        {
            System.Diagnostics.Debug.WriteLine("URL:" + URL);

            Uri requestUri = new Uri(URL);

            //Add a user-agent header to the GET request. 
            var headers = httpClient.DefaultRequestHeaders;

            HttpResponseMessage httpResponse = new HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.PostAsync(requestUri, null);
                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                System.Diagnostics.Debug.WriteLine("Response:" + httpResponseBody);
                return httpResponseBody;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
All Usage Examples Of System.Net.Http.HttpResponseMessage::EnsureSuccessStatusCode