If one desires to run HTTPs server from C#, they might get the following warning:
Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found or is out of date. To generate a developer certificate run 'dotnet dev-certs https'. To trust the certificate (Windows and macOS only) run 'dotnet dev-certs https --trust'. For more information on configuring HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.
And yes, once could follow instructions and have everything running. But where’s the fun in that?
Alternative approach would be to load certificate from the file and .NET makes that really easy.
private static X509Certificate2? GetCertificate() {
var certFilename = Path.Combine(AppContext.BaseDirectory, "my.pfx");
if (File.Exists(certFilename)) {
try {
return new X509Certificate2(certFilename);
} catch (CryptographicException ex) {
// log error or whatever
}
}
return null;
}
So, when bringing server up we can just call it using something like this:
var cert = GetCertificate();
options.Listen(IPAddress.Any, 443, listenOptions => {
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
if (cert != null) {
listenOptions.UseHttps(cert);
} else {
listenOptions.UseHttps();
}
});