2015-02-10 68 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

相关问题