作法:將使用者資訊指派給群組連線

下列範例示範如何將使用者資訊指派給群組連線,並假設應用程式會在呼叫這段程式碼之前設定 UserNameSecurelyStoredPasswordDomain 變數,且 UserName 為唯一。

將使用者資訊指派給群組連線

  1. 建立連線群組名稱。

    SHA1Managed Sha1 = new SHA1Managed();  
    Byte[] updHash = Sha1.ComputeHash(Encoding.UTF8.GetBytes(UserName + SecurelyStoredPassword + Domain));  
    String secureGroupName = Encoding.Default.GetString(updHash);  
    
    Dim Sha1 As New SHA1Managed()  
    Dim updHash As [Byte]() = Sha1.ComputeHash(Encoding.UTF8.GetBytes((UserName + SecurelyStoredPassword + Domain)))  
    Dim secureGroupName As [String] = Encoding.Default.GetString(updHash)  
    
  2. 建立特定 URL 的要求。 例如,下列程式碼會建立 URL http://www.contoso.com. 的要求

    WebRequest myWebRequest=WebRequest.Create("http://www.contoso.com");  
    
    Dim myWebRequest As WebRequest = WebRequest.Create("http://www.contoso.com")  
    
  3. 設定 Web 要求的認證和連線群組名稱,並呼叫 GetResponse 來擷取 WebResponse 物件。

    myWebRequest.Credentials = new NetworkCredential(UserName, SecurelyStoredPassword, Domain);
    myWebRequest.ConnectionGroupName = secureGroupName;  
    
    WebResponse myWebResponse=myWebRequest.GetResponse();  
    
    myWebRequest.Credentials = New NetworkCredential(UserName, SecurelyStoredPassword, Domain)  
    myWebRequest.ConnectionGroupName = secureGroupName  
    
    Dim myWebResponse As WebResponse = myWebRequest.GetResponse()  
    
  4. 使用 WebRespose 物件之後,關閉回應資料流。

    MyWebResponse.Close();  
    
    MyWebResponse.Close()  
    

範例

// Create a connection group name.  
SHA1Managed Sha1 = new SHA1Managed();  
Byte[] updHash = Sha1.ComputeHash(Encoding.UTF8.GetBytes(UserName + SecurelyStoredPassword + Domain));  
String secureGroupName = Encoding.Default.GetString(updHash);  
  
// Create a request for a specific URL.  
WebRequest myWebRequest=WebRequest.Create("http://www.contoso.com");  
  
myWebRequest.Credentials = new NetworkCredential(UserName, SecurelyStoredPassword, Domain);
myWebRequest.ConnectionGroupName = secureGroupName;  
  
WebResponse myWebResponse=myWebRequest.GetResponse();  
  
// Insert the code that uses myWebResponse.  
  
MyWebResponse.Close();  
' Create a secure group name.  
Dim Sha1 As New SHA1Managed()  
Dim updHash As [Byte]() = Sha1.ComputeHash(Encoding.UTF8.GetBytes((UserName + SecurelyStoredPassword + Domain)))  
Dim secureGroupName As [String] = Encoding.Default.GetString(updHash)  
  
' Create a request for a specific URL.  
Dim myWebRequest As WebRequest = WebRequest.Create("http://www.contoso.com")  
  
myWebRequest.Credentials = New NetworkCredential(UserName, SecurelyStoredPassword, Domain)  
myWebRequest.ConnectionGroupName = secureGroupName  
  
Dim myWebResponse As WebResponse = myWebRequest.GetResponse()  
  
' Insert the code that uses myWebResponse.  
MyWebResponse.Close()  

另請參閱