System.Net.Http.dll 中发生了 'System.FormatException' 类型的未处理异常

An unhandled exception of type 'System.FormatException' occurred in System.Net.Http.dll

我正在尝试将 Httprequest 发送到网络 api 并且我在请求 header 中包含了用户名和密码,但我得到了 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]);
               }
       }
}

如果您使用的是基本身份验证,请像这样创建 AuthenticationHeaderValue

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

参考Basic access authentication