.NET 8 Linux下Kestrel配置X509证书出现ERR_SSL_PROTOCOL_ERROR求助
.NET 6升级到.NET 8后Linux虚拟机上HTTPS端点异常问题
我正在将C#/.NET应用从.NET 6.0升级到Linux虚拟机上的.NET 8.0(本地PC操作),但HTTPS端点无法正常工作。查找解决方案时看到一篇关于Kestrel HTTPS绑定的文档,但不确定是否匹配当前问题,也不知道该怎么修复。
我从本地文件系统读取X509Certificate2的crt/密钥对,用来创建支持HTTPS的IHostBuilder对象,当前代码如下:
var certContents = File.ReadAllText(<local filepath>); var certKeyContents = File.ReadAllText(<local key filepath>); var cert = X509Certificate2.CreateFromPem(certContents, certKeyContents); return Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel(options => { options.AddServerHeader = false; options.Listen(IPAddress.Any, port, ops => { ops.UseHttps(cert); }); } ) .UseStartup<Startup>(); }) .ConfigureLogging(logging => { }) .UseNLog();
测试时,Chrome v122.0和Postman v9.31通常显示“此网站无法提供安全连接”,设置断点后发现请求根本没到达后端,断点从未触发。奇怪的是FireFox能更进一步(似乎可以访问后端),它不会抛出SSL错误,但在尝试访问应用的Keycloak实例(非本地部署)验证SSO令牌时,抛出了IDX20803错误,异常栈如下:
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '<Keycloak URL>'. at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
我还遇到过一些类似模式的IDX20803错误。这段代码在.NET 6中运行正常,肯定是遗漏了.NET新版本的某些配置,求指导!
已尝试的方案
- 在
options.Listen()回调中添加以下代码块- 结果:错误无变化
opt.AllowAnyClientCertificate(); opt.ClientCertificateValidation = (certif, chain, policyErrors) => true; opt.ClientCertificateMode = Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode.AllowCertificate; opt.ServerCertificate = cert; opt.SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Ssl3 | System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.None | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls13 | System.Security.Authentication.SslProtocols.Default; - 在
options.Listen()回调中移除ops.UseHttps(cert)调用- 结果:可调用HTTP接口,但HTTPS仍不可用
- 在Program.cs和Startup.cs开头添加代码:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.SystemDefault | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Tls13;- 结果:错误无变化
- 在Startup.cs的Configure方法中添加
app.UseHttpsRedirection();- 结果:错误无变化
内容的提问来源于stack exchange,提问作者Tyler
相关产品推荐
相关产品推荐

