Web Server Certificate From a File

If you’re dealing with HTTPS on .NET 5, you might have seen the following message:
Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found or is out of date."

Recommendation to solve this is also clear To generate a developer certificate run 'dotnet dev-certs https'. To trust the certificate (Windows and macOS only) run 'dotnet dev-certs https --trust'. And you're pointed toward Microsoft docs for more information.

What's not clear is that you can also load certificate from file and skip the whole system configuration - really useful if you don't have the full system access. For that just configure your builder appropriately:

Code excerpt
Builder = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.ConfigureKestrel(options => {
var cert = GetCertificate();
options.Listen(IPAddress.Any, 443, listenOptions => {
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
listenOptions.UseHttps(cert);
});
});
})
.Build();

In example code above, loading the certificate is done from GetCertificate function; something like this:

GetCertificate()
private static X509Certificate2 GetCertificate() {
return new X509Certificate2("mycertificate.pfx", "");
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.