HttpCompletionOption 列舉
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
指出 HttpClient 作業是否應在回應可用時或讀取包含內容的整個回應訊息之後,視為已完成。
public enum class HttpCompletionOption
public enum HttpCompletionOption
type HttpCompletionOption =
Public Enum HttpCompletionOption
- 繼承
欄位
| 名稱 | 值 | Description |
|---|---|---|
| ResponseContentRead | 0 | 操作應該會在閱讀完整回應內容後完成。 |
| ResponseHeadersRead | 1 | 當有回應可用且標頭被讀取時,操作應立即完成。 內容尚未被閱讀。 |
備註
警告
這個 HttpCompletionOption 值會影響讀取回應時選項中 HttpClient 指定的逾時範圍。 在 HttpClient 相關呼叫方法上,這些方法的逾時會一直適用,直到這些方法完成或回傳為止。 關鍵是,使用該 ResponseHeadersRead 選項時,逾時只會套用到標頭結束與內容開始的範圍。 內容讀取操作需另行逾時,以防伺服器迅速回傳狀態列與標頭,但回傳內容時間過長。 這項考量同樣適用於房產本身 MaxResponseContentBufferSize 。 該限制僅在使用 ResponseContentRead時被強制執行。 以下是一個說明這一點的例子:
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);