使ASP.NET核心3.1应用程序在不安装.NET核心SDK的情况下使用SSL证书



我使用以下PowerShell命令序列生成、安装和使用自签名SSL证书:

$cert = New-SelfSignedCertificate -DnsName @("localhost") -CertStoreLocation "cert:LocalMachineMy"
$certKeyPath = "c:certscontoso.com.pfx"
$password = ConvertTo-SecureString 'password' -AsPlainText -Force
$cert | Export-PfxCertificate -FilePath $certKeyPath -Password $password
$rootCert = $(Import-PfxCertificate -FilePath $certKeyPath -CertStoreLocation 'Cert:LocalMachineRoot' -Password $password)
netsh http add sslcert ipport=0.0.0.0:44357 appid={12345678-db90-4b66-8b01-88f7af2e36bf} certhash=55c6f3cc7464060043cd1b738b93c3ad82caaa43

Ever命令已成功完成。

但当我启动ASP.NET Core 3.1应用程序时,它仍然认为它没有任何证书。

Microsoft.AspNetCore.Server.Kestrel[0]无法启动Kestrel。System.InvalidOperationException:无法配置HTTPS终结点。未指定服务器证书,并且找不到默认的开发人员证书或该证书已过期。若要生成开发人员证书,请运行"dotnet dev certs https"。要信任证书(仅限Windows和macOS(,请运行"dotnet dev certs https--trust"。

不幸的是,dotnet dev-certs httpsdotnet dev-certs https --trust需要安装.NET Core SDK,但它不应该在那里!这是一台生产服务器!

您可以在appsettings.json中配置证书。我认为Certificates.Default房产适合你的案子。您需要将AllowInvalid设置为true才能使用自签名证书。

示例设置appsettings.json:

{
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5000"
},
"HttpsDefaultCert": {
"Url": "https://localhost:5004"
}
},
"Certificates": {
"Default": {
"Path": "<path to .pfx file>",
"Password": "$CREDENTIAL_PLACEHOLDER$",
"AllowInvalid": "true"
}
}
}
}

更多的例子和解释可以在微软文档中找到。

如果您打算自己管理证书(不遵循Microsoft的默认解决机制(,请明确要求Kestrel通过ListenOptions.UseHttps、的适当功能使用您的证书

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-6.0#列表使用https

最常见的是UseHttps(StoreName storeName, string subject, bool allowInvalid, StoreLocation location)

appsettings.json的更改仅适用于在Visual Studio中使用dotnet run或调试时。

最新更新