我正在尝试向网络API发送Httprequest,我在请求标头中包含用户名和密码,但我得到The format of value 'dGVzdGNsaWVudDAyOnBhc3MwMg==' is invalid
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 :(得分:0)
如果您使用的是基本身份验证,请创建AuthenticationHeaderValue
,如下所示:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);
请参阅Basic access authentication作为参考。