我正在研究Kubernettes集群上托管的多个Dotnet Core API,其中一些API确实调用了其他API,这就是在标题中抛出异常的原因。
我是否编辑appsettings.json并将所有https替换为http都没有关系-实际上devops团队的人建议我这样做-因为会抛出相同的异常。
这是我用于http调用的一小段代码:
int idCity = Convert.ToInt32(Utils.GetConfig().GetSection("Settings")["idCity"]);
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(Utils.GetConfig().GetSection("xxx")["xxxx"]);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string queryString = "?startDate=" + startDate + "&endDate=" + endDate + "&idCity=" + idCity;
HttpResponseMessage response = client.GetAsync(queryString).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
var resultHolidays = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return JsonConvert.DeserializeObject<JSONGeneric<HolidayDTO>>(resultHolidays);
}
else
{
return null;
}
}
我有.crt格式的证书副本,并且还尝试过:
string certPath = Path.Combine(_env.ContentRootPath, _configuration.GetSection("Certificate")["certificatePath"]);
string pwd = _configuration.GetSection("Certificate")["certificatePwd"];
HttpClientHandler requestHandler = new HttpClientHandler();
requestHandler.ClientCertificates.Add(new X509Certificate2(certPath, pwd,
X509KeyStorageFlags.MachineKeySet));
using (HttpClient client = new HttpClient(requestHandler))
{
...
}
无济于事,因为抛出了相同的异常。
我不是使用证书的专家,但我确实需要使它起作用,以便能够在Pod中使用api调用其他api,因此将不胜感激。
更新1:“怪异”的事情是,如果我仅复制要请求的url(无论您使用的是http还是https-),然后将其粘贴到安装了证书的浏览器中,它就可以正常工作。如果您在浏览器中复制并粘贴URL的http版本,Kubernettes(或任何人)都将重定向到https版本,但最终会得到结果。 不是来自.Net
答案 0 :(得分:0)
我将从禁用客户端中的证书验证开始,然后查看其行为。您可以这样做:
var httpHandler = new HttpClientHandler {
ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
};
using var httpClient = new HttpClient(httpHandler);
// rest of the code
如果调用成功,则下一步是调整证书验证回调以检查服务器的证书。
注意:在您的示例中,您正在配置客户端证书,这在托管服务并希望根据客户端的证书授权客户端时非常有用,如here所述。从问题描述中,我了解到您需要的是相反的:在客户端中验证服务器证书。
var srvCrt = new X509Certificate2(certPath, pwd);
var httpHandler = new HttpClientHandler {
ServerCertificateCustomValidationCallback = (m, crt, chn, e) => {
return crt.Thumbprint == srvCrt.Thumbprint;
}
};
using var httpClient = new HttpClient(httpHandler);
// rest of the code