基于this,我计划为Kestrel加载一个SSL证书,如下所示:

builder.WebHost.ConfigureKestrel((context, serverOptions) =>
{
    serverOptions.ConfigureHttpsDefaults(listenOptions =>
    {
        var certPath = context.Configuration["CERT_PATH"]; // CERT_PATH would be /path/to/ssl/cert.pem
        listenOptions.ServerCertificate = X509Certificate2.CreateFromPemFile(certPath);
    });
});

在应用程序运行期间,可以更新(续订)证书文件.文件会改变,而不是路径.Kestrel如何获得新的证书?有没有办法定期重新加载使用过的ServerCertificate等?该应用程序将在Docker容器中运行.

推荐答案

您可以使用FileSystemWatcher监视您的证书,并在发生更改时在Changed事件中重新加载它.

ServerCertificateSelector是在每个HTTPS连接上调用的委托,并返回用于该连接的证书.当FileSystemWatcher检测到证书文件发生更改时,它会加载新证书并更新委托返回的证书.这样,即使已建立的连接在下一次进行HTTPS握手时也将使用新证书

Please check the test result first.

enter image description here

My sample Code

using Microsoft.Extensions.FileProviders;
using System.Security.Cryptography.X509Certificates;

namespace WebApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            string certPath = @"C:/certificate.crt";
            string certKeyPath = @"C:/private.key"; ;

            X509Certificate2 currentCertificate = X509Certificate2.CreateFromPemFile(certPath, certKeyPath);

            // Configure Kestrel to use the certificate
            builder.WebHost.ConfigureKestrel(serverOptions =>
            {
                serverOptions.ConfigureHttpsDefaults(listenOptions =>
                {
                    listenOptions.ServerCertificateSelector = (context, name) => currentCertificate;
                });
            });
            
            // Add services to the container.
            builder.Services.AddControllers();
            builder.Services.AddControllersWithViews();

            var app = builder.Build();

            // Set up the file watcher
            var certFileWatcher = new FileSystemWatcher(Path.GetDirectoryName(certPath))
            {
                NotifyFilter = NotifyFilters.LastWrite,
                Filter = Path.GetFileName(certPath)
            };
            //var init = CertificateHelper.ExportToPem(currentCertificate);
            certFileWatcher.Changed += (sender, e) =>
            {
                //var currentCertificateTxt = CertificateHelper.ExportToPem(currentCertificate);
                Console.WriteLine("Certificate file changed. Reloading...");

                System.Threading.Thread.Sleep(1000);

                // Load the new certificate
                currentCertificate = new X509Certificate2(certPath, certKeyPath);
                //currentCertificateTxt = CertificateHelper.ExportToPem(currentCertificate);
            };

            certFileWatcher.EnableRaisingEvents = true;

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory())), 
                RequestPath = "" 
            });

            app.UseRouting();

            app.UseAuthorization();

            app.MapControllers();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

           

            app.Run();
        }
    }
}

Csharp相关问答推荐

System.文本.Json现在总是需要无参数构造函数吗?

PredicateBuilder不是循环工作,而是手动工作

在C#中使用in修饰符

CsWin32如何创建PWSTR的实例,例如GetWindowText

如何创建ASP.NET Core主机并在同一进程中运行请求

在C#WinUI中,一个关于System的崩溃."由于未知原因导致执行不例外"

如何在C#中使用正则表达式抓取用逗号分隔的两个单词?

不带身份的Blazor服务器.Net 8 Cookie身份验证

Int和uint相乘得到LONG?

如何在页面重新加载后保持菜单切换状态

如何将ASP.NET Core 2.1(在.NET框架上运行)更新到较新的版本?

ASP.NET配置kestrel以使用Windows证书存储中的HTTPS

如何在NET 8最小API中自动记录TypedResults.Stream响应

在try 使用访问服务器上的文件夹时,如何解决CORS错误.NET核心API

try 链接被委派者(多播委托)时,无法将获取运算符应用于类型为';方法组&39;和方法组';的操作数

使用C#和.NET 7.0无法访问Cookie中的数据

为什么当我try 为玩家角色设置动画时,没有从文件夹中拉出正确的图像?

根据优先级整理合同列表

无法使用直接URL通过PictureBox.ImageLocation加载图像

C#-如何将int引用获取到byte[]