.NET API Documentation

HttpCompletionOption Enum

Specifies when an asynchronous HTTP operation should complete.

Namespace

System.Net.Http

Inheritance

System.Object
System.ValueType
System.Enum
System.Net.Http.HttpCompletionOption

Remarks

When you call methods such as HttpClient.GetAsync and HttpClient.SendAsync, you can specify an HttpCompletionOption value to control when the asynchronous operation returns.

  • HttpCompletionOption.ResponseContentRead: The asynchronous operation completes when the entire HTTP response content has been read and deserialized. This is the default value.
  • HttpCompletionOption.ResponseHeadersRead: The asynchronous operation completes when the response headers are available. The content is not read until later.

Using ResponseHeadersRead can improve performance for scenarios where you do not need the entire response content immediately. For example, if you only need to check the response status code or headers, you can use ResponseHeadersRead to get the HttpResponseMessage object sooner, and then read the content only if necessary.

Members

Member name Description
ResponseContentRead The asynchronous operation completes when the entire HTTP response content has been read and deserialized.
ResponseHeadersRead The asynchronous operation completes when the response headers are available.

Example

The following example demonstrates how to use HttpCompletionOption.ResponseHeadersRead:

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
            {
                // Use ResponseHeadersRead to get the response message as soon as headers are available
                HttpResponseMessage response = await client.GetAsync("https://www.example.com", HttpCompletionOption.ResponseHeadersRead);

                // Check if the request was successful
                response.EnsureSuccessStatusCode();

                // You can now inspect headers or status code before reading the content
                Console.WriteLine($"Status Code: {response.StatusCode}");
                Console.WriteLine($"Content-Type: {response.Content.Headers.ContentType?.MediaType}");

                // Read the content only when needed
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response body received.");
                // Process the responseBody...
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
        }
    }
}