2015-02-10 69 views
0

我試圖發送一個HTTPRequest,對Web API,我,包括請求頭的用戶名和密碼,但我得到The format of value 'dGVzdGNsaWVudDAyOnBhc3MwMg==' is invalid型「System.FormatException」未處理的異常發生在System.Net.Http.dll

 HttpClientHandler handler = new HttpClientHandler(); 
     HttpClient client = new HttpClient(handler); 
     String userName = "testclient02"; 
     String userPassword = "pass02"; 

     string authInfo = userName + ":" + userPassword; 
     authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); 

     // client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", authInfo);//if use this i get 2 authorization tags in header- Authorization: Authorization XXXXXXXXX=== 
     client.DefaultRequestHeaders.Add("Authorization", authInfo.ToString());//error here 

     var result = client.GetAsync(new Uri("http://localhost:007/api/XXX")).Result; 

編輯:這是我的解碼碼

public class AuthenticationHandler : DelegatingHandler 
    { 
     public User ObjUser; 
     protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
     { 
      try 
      { 
       var tokens = request.Headers.GetValues("Authorization").FirstOrDefault(); 
       if (tokens != null) 
       { 
        byte[] data = Convert.FromBase64String(tokens); 
        string decodedString = Encoding.UTF8.GetString(data); 
        string[] tokensValues = decodedString.Split(':'); 

        ObjUser = new CredentialChecker().CheckCredential(tokensValues[0], tokensValues[1]); 
       } 
     } 
} 

回答

0

如果您正在使用基本身份驗證,然後創建AuthenticationHeaderValue這樣的:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo); 

請參閱Basic access authentication作爲參考。

+0

你可以給我一些建議/代碼示例解碼與基本認證 – prasy 2015-02-11 22:26:05

+0

我也添加了解碼代碼。 – prasy 2015-02-11 22:35:38

+0

@prasy看看這個博客:http://weblog.west-wind.com/posts/2013/Apr/18/A-WebAPI-Basic-Authentication-Authorization-Filter – 2015-02-11 23:05:11

相關問題