2014-01-29 49 views
1

我有必須返回一個value.Here我的要求是一個方法的web服務,我想通過在標題爲每個和認證值的每個Web請求我用下面的給定的代碼做同樣的如何在webservice中傳遞基本身份驗證?

req = WebRequest.Create(http://localhost/test/test.asmx); 
string _auth = string.Format("{0}:{1}", "username", "password"); 
string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth)); 
string _cred = string.Format("{0} {1}", "Basic", _enc); 
req.Headers[HttpRequestHeader.Authorization] = _cred; 
WebResponse response = (WebResponse)req.GetResponse(); 

但通過這種方式,我無法調用webmethod。有什麼辦法可以達到同樣的效果嗎?

我也試着用下面給定的代碼ICredentials的幫助下發送的驗證值,但我需要像頭值「授權:基本YWRtaW46YWRtaW4 =」

ICredentials creds; 
creds = new 
NetworkCredential("username", "password", "domain"); 
proxy.Credentials = creds; 
string str=proxy.helloworld(); 

請讓我知道,如果有是任何方式來實現這個..任何幫助表示讚賞。

感謝

回答

1

this post複製。

protected override System.Net.WebRequest GetWebRequest(Uri uri) 
{ 
    HttpWebRequest request; 
    request = (HttpWebRequest)base.GetWebRequest(uri); 

    if (PreAuthenticate) 
    { 
     NetworkCredential networkCredentials = 
       Credentials.GetCredential(uri, 「Basic」); 

     if (networkCredentials != null) 
     { 
      byte[] credentialBuffer = new UTF8Encoding().GetBytes(
       networkCredentials.UserName + 「:」 + 
       networkCredentials.Password); 
      request.Headers["Authorization"] = 
       「Basic」 + Convert.ToBase64String(credentialBuffer); 
     } 
     else 
     { 
      throw new ApplicationException(「No network credentials」); 
     } 
    } 
    return request; 
}