首页 > 解决方案 > 在 .NET 控制台应用程序中为 Kestrel WebHost 构建器配置 SSL 证书

问题描述

我正在控制台应用程序中创建一个 ASP.NET Web API 端点,我需要将其作为 Windows 服务托管。

现在一切正常,除了端点在 http 中。我想使用https。

当我通过 Visual Studio 运行它时。

我相信 Kestrel 在 IIS 后面,因为它是一个反向代理,并且 SSL 证书已经过验证。但是当我将它作为 Windows 服务托管时。尝试到达端点时遇到证书错误

这是我的 Kestrel WebHost 构建器

var configigurations = new ConfigurationBuilder()
                       .AddJsonFile("appsettings.json", optional: false)
                       .Build();
var host = new WebHostBuilder()
                .UseKestrel(options =>
                {
                    options.ListenAnyIP(443, listenOptions =>
                    {
                        listenOptions.UseHttps("sslcertificate.pfx", "ssl@123");
                    });
                })
                .UseUrls(config.ApiBaseUrl)
                .UseConfiguration(configigurations)
                .UseStartup<Startup>()
                .Build();
host.Run();

由于它作为 Windows 服务运行并公开 API,因此我不能依赖 IIS。我需要为 Kestrel 进行配置。

但我怎么能

  1. 为 localhost 生成 SSL(我使用的是 Windows)

  2. 如果我已经在生产中使用 SSL 证书 (*.cert)。如何在生产服务器(也是 Windows)上使用它制作 *.pfx(证书 + RSA 私钥)

标签: c#.netsslkestrel

解决方案


  1. .Net Core(和 .Net 5)捆绑了一个方便的工具来处理开发自签名证书。查看dotnet dev-certs。命令是:
dotnet dev-certs https -ep $env:USERPROFILE\.aspnet\https\aspnetapp.pfx -p crypticpassword
dotnet dev-certs https --trust

该文档还描述了如何使用 PowerShell 或 openssl 做同样的事情,如果那是你的风格

  1. 看看这个问题。简而言之,您可以通过从 Windows 证书存储中导出证书并选择自动启用 PFX 格式的“是,导出私钥”来做到这一点

推荐阅读