您可以使用FileSystemWatcher
监视您的证书,并在发生更改时在Changed事件中重新加载它.
ServerCertificateSelector是在每个HTTPS连接上调用的委托,并返回用于该连接的证书.当FileSystemWatcher检测到证书文件发生更改时,它会加载新证书并更新委托返回的证书.这样,即使已建立的连接在下一次进行HTTPS握手时也将使用新证书
Please check the test result first.个
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();
}
}
}