HttpCompletionOption Enum
Specifies when an HttpClient operation should complete.
Namespace: System.Net.Http
Assembly: System.Net.Http.dll
Syntax
Members
The HttpCompletionOption enumeration defines the following members:
-
ResponseContentRead
Indicates that the operation should complete only after the entire HTTP content has been read. This is the default behavior. -
ResponseHeadersRead
Indicates that the operation should complete as soon as the response headers are received and the connection is established. The content will not be read at this point.
Remarks
The HttpCompletionOption enumeration is used with methods such as HttpClient.SendAsync and HttpClient.GetAsync.
By specifying HttpCompletionOption.ResponseHeadersRead, you can start processing the response headers and potentially stream the content without waiting for the entire content to be downloaded, which can be beneficial for large responses.
Example
The following example demonstrates how to use HttpCompletionOption.ResponseHeadersRead to get a response without downloading the full content immediately.
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
public static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
try
{
// Create a request message
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://www.example.com");
// Send the request and complete only after headers are read
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
// Check if the request was successful
response.EnsureSuccessStatusCode();
Console.WriteLine($"Status Code: {response.StatusCode}");
Console.WriteLine("Response headers received. Content is ready to be read.");
// Now you can read the content if needed
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Content length: {content.Length} characters.");
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
}
}