我使用以下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 https
和dotnet 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
或调试时。