Bagikan melalui


HttpCompletionOption Enum

Definisi

Menunjukkan apakah operasi HttpClient harus dianggap selesai segera setelah respons tersedia, atau setelah membaca seluruh pesan respons termasuk konten.

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

Bidang

Nama Nilai Deskripsi
ResponseContentRead 0

Operasi harus selesai setelah membaca seluruh respons termasuk konten.

ResponseHeadersRead 1

Operasi harus selesai segera setelah respons tersedia dan header dibaca. Konten belum dibaca.

Keterangan

Peringatan

Nilai HttpCompletionOption memengaruhi cakupan batas waktu yang ditentukan dalam HttpClient opsi saat membaca respons. Batas waktu pada HttpClient selalu berlaku pada metode yang dipanggil yang relevan hingga titik di mana metode tersebut selesai/dikembalikan. Sangat penting, saat menggunakan ResponseHeadersRead opsi , batas waktu hanya berlaku hingga di mana header berakhir dan konten dimulai. Operasi pembacaan konten perlu kehabisan waktu secara terpisah jika server segera mengembalikan baris status dan header tetapi membutuhkan waktu terlalu lama untuk mengembalikan konten. Pertimbangan ini juga berlaku untuk MaxResponseContentBufferSize properti . Batas hanya diberlakukan saat menggunakan ResponseContentRead. Di bawah ini adalah contoh yang mengilustrasikan poin ini:

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

Berlaku untuk