I know this was asked a while ago, but I think it would make sense to post on this one as the ASP.NET Core framework has been enhanced to support Kestrel endpoint configuration from application settings since this question was initially asked.
Please find below more details and a little summary on how to achieve that in ASP.NET Core 2.1 and earlier versions.
It is possible to configure Kestrel endpoints in application settings starting from ASP.NET Core version 2.1, as also stated in the documentation.
For further details, it is possible to check in the actual WebHost.CreateDefaultBuilder() implementation:
from release 2.1, it loads the Kestrel
configuration section, while on ASP.NET Core earlier versions it is necessary to explicitly call UseKestrel()
when setting up your WebHost
.
ASP.NET Core 2.1 setup
On ASP.NET Core 2.1, you can setup Kestrel to listen at http://127.0.0.1:5011
by simply providing the following appsettings.json
:
{
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://127.0.0.1:5011"
}
}
}
}
Note you will need to use Url
instead of Address
and Port
.
ASP.NET Core 2.0 setup
On ASP.NET Core 2.0 this very same behavior can be achieved by explicitly calling UseKestrel()
in Program.cs
. You may use an extension method to keep your Program.cs
clean:
public class Program {
public static void Main(string[] args) {
// configuration
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true)
.AddCommandLine(args)
.Build();
// service creation
var webHost = WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrelEndpoints(config) // extension method to keep things clean
.UseConfiguration(config)
.UseApplicationInsights()
.Build();
webHost.Run();
}
}
The UseKestrelEndpoints()
is an extension method that looks into the actual configuration settings and setup Kestrel options accordingly:
public static IWebHostBuilder UseKestrelEndpoints(this IWebHostBuilder webHostBuilder, IConfiguration configuration) {
var endpointSection = configuration.GetSection("kestrel:endpoints");
if (endpointSection.Exists()) {
webHostBuilder.UseKestrel(options => {
// retrieve url
var httpUrl = endpointSection.GetValue<string>("http:url", null);
/* setup options accordingly */
});
}
return webHostBuilder;
}
If needed, you may setup HTTPS in a similar way.