我正在本地开发一个 Web API 和一个 Web 应用程序。我在从 Web 应用程序调用 Web API 时遇到问题。
当我调用它时,我不断收到错误:“根据验证程序,远程证书无效。”
这两个应用程序都是使用 ASP.Net Core 构建的,并在 kestrel 上运行。该网络应用程序可调用为 https://mylibrary.com:5003 Web API 可调用为 https://api.mylibrary.com:5001 .
如何让它们与有效的证书一起工作?
编辑:意识到问题是应用程序默认使用本地主机证书。我希望能够使用我自己的自签名证书。
如果有人可以向我指出解释如何设置两个应用程序以在 .net core Web 项目中使用自签名证书的地方,请这样做:)
最佳答案
如果您需要使用 HttpClient 解决证书验证问题,您可以按照 Rohit Jangid's answer 创建 HttpClientHandler 并将其传递给 HttpClient 来完成此操作。至 The SSL connection could not be established
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
HttpClient client = new HttpClient(clientHandler)
通过检查是否在开发环境中,避免在生产中意外规避证书验证:
HttpClient httpClient = new HttpClient();
if (env.IsDevelopment())
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, ssl) => { return true; };
httpClient = new HttpClient(clientHandler);
}
通过将有关 webhostenvironment 的信息注入(inject)到处理程序/操作中来注入(inject)它:
public async Task OnGet([FromServices] IWebHostEnvironment env)
关于ssl - 从 Web App 调用 Web API 时出现证书问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59926115/