Rediger

Del via


HttpCompletionOption Enum

Definition

Indicates if HttpClient operations should be considered completed either as soon as a response is available, or after reading the entire response message including the content.

public enum class HttpCompletionOption
public enum HttpCompletionOption
type HttpCompletionOption = 
Public Enum HttpCompletionOption
Inheritance
HttpCompletionOption

Fields

Name Value Description
ResponseContentRead 0

The operation should complete after reading the entire response including the content.

ResponseHeadersRead 1

The operation should complete as soon as a response is available and headers are read. The content is not read yet.

Remarks

Warning

The HttpCompletionOption value affects the scope of the timeout specified in the HttpClient options when reading a response. The timeout on the HttpClient always applies on the relevant invoked methods up until the point where those methods complete/return. Crucially, when using the ResponseHeadersRead option, the timeout applies only up to where the headers end and the content starts. The content reading operation needs to be timed out separately in case the server promptly returns the status line and headers but takes too long to return the content. This consideration also applies to the MaxResponseContentBufferSize property. The limit is only enforced when using ResponseContentRead. Below is an example illustrating this point:

using var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromSeconds(30);
httpClient.MaxResponseContentBufferSize = 1_000; // This will be ignored

// Because we're specifying the ResponseHeadersRead option,
// the 30-second timeout applies only up until the headers are received.
// It does not affect future operations that interact with the response content.
using HttpResponseMessage response = await httpClient.GetAsync(
    "http://localhost:12345/",
    HttpCompletionOption.ResponseHeadersRead);

// Do other checks that don't rely on the content first, like status code validation.
response.EnsureSuccessStatusCode();

// Since the HttpClient.Timeout will not apply to reading the content,
// you must enforce it yourself, for example by using a CancellationTokenSource.
using var cancellationSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));

// If you wish to enforce the MaxResponseContentBufferSize limit as well,
// you can do so by calling the LoadIntoBufferAsync helper first.
await response.Content.LoadIntoBufferAsync(1_000, cancellationSource.Token);

// Make sure to pass the CancellationToken to all methods.
string content = await response.Content.ReadAsStringAsync(cancellationSource.Token);

Applies to