HttpResponseMessage Class
Represents an HTTP response message received from an HTTP server.
System.Object
System.Net.Http.HttpResponseMessage
public sealed class HttpResponseMessage : System.IDisposable
Summary
- Represents an HTTP response message.
- Contains the status code and reason phrase.
- Holds the HTTP content.
- Provides properties for headers and request message.
- Implements
IDisposablefor proper resource management.
Constructors
public HttpResponseMessage(System.Net.HttpStatusCode statusCode)
Initializes a new instance of the HttpResponseMessage class with a specified HTTP status code.
public HttpResponseMessage()
Initializes a new instance of the HttpResponseMessage class.
Properties
| Name | Description |
|---|---|
Content |
Gets or sets the HTTP content of the response. |
RequestMessage |
Gets or sets the HttpRequestMessage which led to this response. |
ReasonPhrase |
Gets or sets the HTTP status code reason phrase. |
StatusCode |
Gets or sets the HTTP status code. |
Version |
Gets or sets the HTTP message version. |
Methods
| Name | Description |
|---|---|
EnsureSuccessStatusCode() |
Throws an exception if the response was not successful. |
Dispose() |
Releases the unmanaged resources that are used by the HTTP response message. |
ToString() |
Returns a string that represents the current object. |
Examples
The following example sends an HTTP GET request and processes the response.
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
public static async Task Main(string[] args)
{
using (var client = new HttpClient())
{
try
{
var response = await client.GetAsync("https://www.microsoft.com");
if (response.IsSuccessStatusCode)
{
// Process the successful response
Console.WriteLine($"Status Code: {response.StatusCode}");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Content Length: {content.Length}");
}
else
{
// Handle non-success status codes
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
}
// Alternatively, use EnsureSuccessStatusCode to throw an exception on failure
response.EnsureSuccessStatusCode();
var content2 = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Request succeeded. Content length: {content2.Length}");
}
catch (HttpRequestException e)
{
Console.WriteLine($"An error occurred: {e.Message}");
}
}
}
}