[英]An unhandled exception of type 'System.FormatException' occurred in System.Net.Http.dll
I am trying to send a Httprequest to web api and i am including the username and password in request header, but i get The format of value 'dGVzdGNsaWVudDAyOnBhc3MwMg==' is invalid
我正在尝试向Web 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;
edit: This my decoding code 编辑:这是我的解码代码
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]);
}
}
}
If you are using basic authentication then create AuthenticationHeaderValue
like this: 如果使用的是基本身份验证,则创建AuthenticationHeaderValue
如下所示:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);
See Basic access authentication as a reference. 请参阅基本访问身份验证作为参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.