This feels like a simple problem to solve, but in all my searching I'm still yet to find a solution that works for me. Could be another case of not finding what I'm after as I'm not searching the right 'thing', but here we are..
I have a C# Web API program where I want to configure the kestrel server from a config object.
I receive this config into my service via rest call, into a CustomConfig object. I can get this config object either in Program.cs or in Startup.cs, but since I don't want to repeat myself and make additional calls, I don't want to do this in both places.
My preference is to get the config in Startup.cs since that's where the rest of my configuration code sits, and is where I'm already using my CustomConfig object. However, I can't find a way to configure the kestrel server to use the certificate I'm giving it (in Startup.cs), nor can I see a way to inject this config into Startup.cs from Program.cs.
In other projects I have passed the location of the PFX file as an environment variable: ASPNETCORE_Kestrel__Certificates__Default__Path (in which case everything works without additional code config), but in this project all config must be retrieved via rest call, so this is not an option here.
I currently have everything running, but only by making the rest call to get config twice. The current implementation to configure kestrel is storing the PFX in CustomConfig as a base64 string, and configuring in Program.cs:
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
CustomConfig config = CustomConfig() // <- I receive config here
webBuilder.UseStartup<Startup>();
webBuilder.UseKestrel(options =>
{
options.ConfigureHttpsDefaults(d =>
{
byte[] pfxBytes = Convert.FromBase64String(config.Base64PFXBytes);
d.ServerCertificate = new X509Certificate2(pfxBytes, "sslKey");
});
});
});
}
To summarise..
- I have a
CustomConfigobject which is used to configure services inStartup.cs - I want to configure my Kestrel server from my
CustomConfig
So I'm looking for help to either:
- Get Kestrel to use my PFX within
Startup.cs - Pass the
CustomConfigobject fromProgram.csintoStartup.cs
Hopefully that makes sense.. Welcome any & all solutions / additional questions for clarity!
Thanks in advance!