【问题标题】:An unhandled exception of type 'System.FormatException' occurred in System.Net.Http.dllSystem.Net.Http.dll 中出现“System.FormatException”类型的未处理异常
【发布时间】:2015-02-12 06:35:01
【问题描述】:

我正在尝试向 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;

编辑:这是我的解码代码

  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]);
               }
       }
}

【问题讨论】:

    标签: c# asp.net-web-api


    【解决方案1】:

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

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

    请参阅 Basic access authentication 作为参考。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多