Overview Fields Properties Methods Remarks Examples Inheritance Implements

System.Net.Http.HttpResponseMessage Class

Represents an HTTP response message, including the status code and data.

In the .NET Framework, the HttpResponseMessage class is a core component for working with HTTP responses when using the HttpClient class. It encapsulates all the information that a server sends back to a client after processing an HTTP request. This includes the HTTP version, status code, reason phrase, headers, and the content of the response.

This class is part of the System.Net.Http namespace, which provides classes for sending HTTP requests and receiving HTTP responses.

Inheritance

public class HttpResponseMessage : IDisposable

object

Implemented interfaces:

Fields

This class has no fields.

Properties

Methods

Remarks

The HttpResponseMessage class is fundamental to consuming HTTP services in .NET. When you use HttpClient.SendAsync() or HttpClient.GetAsync(), the result is an HttpResponseMessage.

Key aspects of HttpResponseMessage:

Examples

Here's a common scenario demonstrating how to use HttpResponseMessage:

using System.Net.Http; using System.Threading.Tasks; public class Example { public async Task FetchDataAsync() { using (var client = new HttpClient()) { try { HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1"); // Check if the request was successful response.EnsureSuccessStatusCode(); // Throws an exception for non-2xx status codes // Access response properties HttpStatusCode statusCode = response.StatusCode; string reasonPhrase = response.ReasonPhrase; bool isSuccess = response.IsSuccessStatusCode; // Read the response content if (response.Content is not null) { string responseBody = await response.Content.ReadAsStringAsync(); System.Console.WriteLine($"Status Code: {statusCode}"); System.Console.WriteLine($"Reason Phrase: {reasonPhrase}"); System.Console.WriteLine($"Response Body: {responseBody}"); } } catch (HttpRequestException e) { System.Console.WriteLine($"Request exception: {e.Message}"); } } } }

In this example: