.NET API Browser

HttpCompletionOption Enum

Specifies when an HttpClient operation should complete.

Namespace: System.Net.Http
Assembly: System.Net.Http.dll

Syntax

public enum HttpCompletionOption

Members

The HttpCompletionOption enumeration defines the following members:

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}");
            }
        }
    }
}
            

See Also