.NET Core 3.1轻松获取基本身份验证-401未经授权

时间:2020-10-30 18:45:24

标签: rest basic-authentication asp.net-core-3.1

我目前正在将.NET 4.7.2应用程序移植到.NET Core 3.1的过程中,并且在进行API调用时遇到了问题(相同的代码在4.7.2中很好用,但在Core 3.1中不起作用)。唯一的区别是我不得不在新应用中绕过证书验证。这是代码:

全局变量:

    private static HttpClient _client; 

构造函数

    if (_client == null)
    {
        SetHttpClient();
    }

用于初始化HttpClient的代码

    private void SetHttpClient()
    {
        // Setup Basic Authenticaiton for the requests
        string username = _config.Value.Domain + @"\" + _config.Value.ServiceUsername;
        string password = _config.Value.ServicePassword;

        // The API does not have certificates in the xxxx domain, bypass cert validation
        if (_config.Value.Domain.ToUpper() == "xxxx")
        {
            // SSL isn't setup so don't check the Cert
            HttpClientHandler clientHandler = new HttpClientHandler();
            clientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

            // Initialize the Client
            _client = new HttpClient(clientHandler);
        }
        else
        {
            _client = new HttpClient();
        }

        // Setup basic authentication
        string encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
        _client.DefaultRequestHeaders.Add("Authorization", "Basic " + encoded);
    }

最后是请求

    string url = _config.Value.ServiceUrl + _employee.Id;
    var response = _client.GetStringAsync(url).Result;

0 个答案:

没有答案