WebClient.Headers 屬性

定義

取得或設定與要求相關聯的標頭名稱/值組集合。

C#
public System.Net.WebHeaderCollection Headers { get; set; }

屬性值

WebHeaderCollection,其中包含與此要求相關聯的標頭名稱/值組。

範例

下列程式代碼範例會使用 Headers 集合,將 HTTP Content-Type 標頭設定為 application/x-www-form-urlencoded,,以通知伺服器表單數據已附加至貼文。

C#
   string uriString;
       Console.Write("\nPlease enter the URI to post data to {for example, http://www.contoso.com} : ");
       uriString = Console.ReadLine();

       // Create a new WebClient instance.
       WebClient myWebClient = new WebClient();
       Console.WriteLine("\nPlease enter the data to be posted to the URI {0}:",uriString);
       string postData = Console.ReadLine();
       myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");

 // Display the headers in the request
       Console.Write("Resulting Request Headers: ");
       Console.WriteLine(myWebClient.Headers.ToString());
       
       // Apply ASCII Encoding to obtain the string as a byte array.

       byte[] byteArray = Encoding.ASCII.GetBytes(postData);
       Console.WriteLine("Uploading to {0} ...",  uriString);						
       // Upload the input string using the HTTP 1.0 POST method.
       byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);
       
       // Decode and display the response.
       Console.WriteLine("\nResponse received was {0}",
       Encoding.ASCII.GetString(responseArray));
                 

備註

警告

WebRequestHttpWebRequestServicePointWebClient 已經過時,您不應該將它們用於新的開發。 請改用 HttpClient

Headers 屬性包含 WebHeaderCollection 實例,其中包含 WebClient 與要求一起傳送的通訊協議標頭。

某些常見的標頭會被視為受限制,並且受到系統保護,而且無法在 WebHeaderCollection 對象中設定或變更。 嘗試在與 WebClient 對象相關聯的 WebHeaderCollection 對象中設定其中一個受限制的標頭,稍後嘗試傳送 WebClient 要求時,都會擲回例外狀況。

受系統保護的受限制標頭包含,但不限於下列各項:

  • 日期

  • 主機

此外,使用 WebClient 物件時,也會限制一些其他標頭。 這些受限制的標頭包括,但不限於下列各項:

  • 接受

  • 連接

  • Content-Length

  • 預期 (當值設定為 “100-continue” 時

  • If-Modified-Since

  • 範圍

  • Transfer-Encoding

HttpWebRequest 類別具有屬性,可設定上述部分標頭。 如果應用程式必須設定這些標頭,則應該使用 HttpWebRequest 類別,而不是 WebRequest 類別。

您不應該假設標頭值會保持不變,因為 Web 伺服器和快取可能會變更或新增標頭至 Web 要求。

適用於

產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

另請參閱