Represents an HTTP response message received from an HTTP server.

This class is used to represent the HTTP response, including the status code, headers, and content.

Constructors

Signature Description
HttpResponseMessage() Initializes a new instance of the HttpResponseMessage class with a default HttpStatusCode.OK status.
HttpResponseMessage(HttpStatusCode statusCode) Initializes a new instance of the HttpResponseMessage class with a specified HttpStatusCode.

Properties

Name Type Description
Content HttpContent? Gets or sets the HTTP content of the response.
Headers HttpResponseHeaders Gets the collection of HTTP response headers.
IsSuccessStatusCode bool Gets a value indicating whether the HTTP response was successful. Success is defined as status codes in the range 200–299.
ReasonPhrase string? Gets or sets the reason phrase associated with the HTTP status code.
RequestMessage HttpRequestMessage? Gets or sets the HTTP request message that led to this response message.
StatusCode HttpStatusCode Gets or sets the status code of the HTTP response.
Version Version Gets or sets the HTTP protocol version.

Methods

Signature Description
EnsureSuccessStatusCode() Throws an exception if the HTTP response was not successful.
EnsureSuccessStatusCode(string? message) Throws an exception if the HTTP response was not successful, with a custom message.
Dispose() Releases the unmanaged resources and optionally releases the managed resources used by the HttpResponseMessage.
Dispose(bool disposing) Releases the unmanaged resources and optionally releases the managed resources used by the HttpResponseMessage.
ToString() Returns a string that represents the current object.

See Also

Example Usage

Here's a simple example of how to use HttpResponseMessage:


using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Example
{
    public static async Task MakeRequest()
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync("https://www.example.com");
                response.EnsureSuccessStatusCode(); // Throws if status code is not 2xx

                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response Body:");
                Console.WriteLine(responseBody);

                Console.WriteLine($"Status Code: {response.StatusCode}");
                Console.WriteLine($"Reason Phrase: {response.ReasonPhrase}");

                foreach (var header in response.Headers)
                {
                    Console.WriteLine($"Header: {header.Key} = {string.Join(", ", header.Value)}");
                }
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request exception: {e.Message}");
            }
        }
    }
}