HTTPClient to API, Certificate and SSL errors

时间:2018-09-19 08:18:30

标签: c# asp.net-core-webapi asp.net-core-2.1

I've created a ASP.Net Core 2.1 web application which gathers data from two sources. One is a SQL-database which supplies data via Entity Framework to my application. This one works fine. The other source is a REST API. I'm having troubles connecting to this.

I'm calling this Task which should return a user via his/hers e-mail address:

        public async Task<PersonsModel> ReturnPersonByEmail(string email)
    {
        const string apiKey = "xxx";

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://xx.xxx.xxxx.xx:xxx/xxxx/xxx/xx/xx/person/?email={email}");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("x-api-key", "123456");
            var url = new Uri(client.BaseAddress.ToString());

            string json = "";

            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                var response = await client.GetAsync(url);

                using (var content = response.Content)
                {
                    json = await content.ReadAsStringAsync();
                }
            }
            catch (Exception e)
            {
                var exception = e;
            }

            return JsonConvert.DeserializeObject<PersonsModel>(json);
        }
    }
}

When I try calling it via Postman client.GetAsync(url) always returns an exception:

Message = "The remote certificate is invalid according to the validation procedure." Message = "The SSL connection could not be established, see inner exception."

I tried adding the following codesegment to launchSettings.json(as per a reply to a similar question posted here: HttpClient client.GetAsync works in full .Net framework but not in .Net core 2.1? ) "DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER": "0" and then I get another error:

Message = "Error 12175 calling WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, 'A security error has occurred'."

If you have any idea on what might cause this problem I would be very grateful for any help. Thanks!

0 个答案:

没有答案