具有基本身份验证的Web API

时间:2019-05-28 15:08:16

标签: c# basic-authentication dotnet-httpclient

我正在调用一个Web api,它需要使用以下代码进行基本身份验证:

using (var handler = new HttpClientHandler() { DefaultProxyCredentials = CredentialCache.DefaultCredentials } )
{
            handler.PreAuthenticate = true;
            using (var client = new HttpClient(handler))
            {
                var byteArray = Encoding.ASCII.GetBytes($"{UId}:{Pwd}");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                var response = await client.GetAsync(url);

                // if status code is 401, retry.
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                    response = await client.GetAsync(url);
            }
}

API始终返回401,我必须重试(有效)。我尝试添加PreAuthenticate,但没有帮助。

要解决此问题,是否需要进行其他任何更改?

0 个答案:

没有答案