WebClient.Credentials 屬性

定義

取得或設定傳送至主機並用於驗證要求的網路認證。

public:
 property System::Net::ICredentials ^ Credentials { System::Net::ICredentials ^ get(); void set(System::Net::ICredentials ^ value); };
public System.Net.ICredentials? Credentials { get; set; }
public System.Net.ICredentials Credentials { get; set; }
member this.Credentials : System.Net.ICredentials with get, set
Public Property Credentials As ICredentials

屬性值

ICredentials,包含要求的驗證認證。 預設為 null

範例

下列程式碼範例會使用使用者的系統認證來驗證要求。

int main()
{
   try
   {
      WebClient^ client = gcnew WebClient;
      client->Credentials = CredentialCache::DefaultCredentials;
      array<Byte>^pageData = client->DownloadData( "http://www.contoso.com" );
      String^ pageHtml = Encoding::ASCII->GetString( pageData );
      Console::WriteLine( pageHtml );
   }
   catch ( WebException^ webEx ) 
   {
      Console::Write( webEx );
   }

}

public static void Main()
{           
    try {

        WebClient client = new WebClient();

        client.Credentials = CredentialCache.DefaultCredentials;

        Byte[] pageData = client.DownloadData("http://www.contoso.com");
        string pageHtml = Encoding.ASCII.GetString(pageData);
        Console.WriteLine(pageHtml);
    } catch (WebException webEx) {
        Console.Write(webEx.ToString());
    }
}    
Public Shared Sub Main()
    Try
        Dim client As New WebClient()

        client.Credentials = CredentialCache.DefaultCredentials

        Dim pageData As [Byte]() = client.DownloadData("http://www.contoso.com")
        Dim pageHtml As String = Encoding.ASCII.GetString(pageData)
        
        Console.WriteLine(pageHtml)

    Catch webEx As WebException
        Console.Write(webEx.ToString())
    End Try
End Sub 

備註

Credentials屬性包含用來存取主機上資源的驗證認證。 在大部分的用戶端案例中 DefaultCredentials ,您應該使用 ,這是目前登入使用者的認證。 若要這樣做,請將 UseDefaultCredentials 屬性設定為 true ,而不是設定此屬性。

WebClient如果在仲介層應用程式中使用 類別,例如 ASP.NET 應用程式, DefaultCredentials 則 屬於執行 ASP 頁面的帳戶, (伺服器端認證) 。 一般而言,您會將此屬性設定為代表提出要求之用戶端的認證。

基於安全性考慮,在自動追蹤重新導向之後,請將您想要包含在 重新導向中的 CredentialCache 認證儲存,並將其指派給此屬性。 如果此屬性包含 以外的任何專案 CredentialCache ,則此屬性會在重新導向時自動設定為 null 。 在這些情況下,將這個屬性值自動設定為 null ,可防止將認證傳送至任何非預期的目的地。

適用於

另請參閱