May 27, 2016

How to configure Kestrel URLs in ASP.NET Core RC2

Prior to the release of ASP.NET Core RC2 Kestrel would be configured as part of the command bindings in project.json:

"commands": {
  "web": "Microsoft.AspNet.Server.Kestrel --server.urls=http://localhost:60000;http://localhost:60001;"
},

If no URLs were specified, a default binding of http://localhost:5000 would be used.

As of RC2 we have a new unified toolchain (the .NET Core CLI) and ASP.NET Core applications are effectively just .NET Core Console Applications. They have a single entry point where we programatically configure and run the web host:

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

Here we’re adding support for both Kestrel and IIS hosts via the appropriate extension methods.

When we upgraded SaasKit to RC2 we used the UseUrls extension to configure the URLs Kestrel would bind to:

var host = new WebHostBuilder()
	.UseKestrel()
	.UseContentRoot(Directory.GetCurrentDirectory())
	.UseUrls("http://localhost:60000", "http://localhost:60001")
	.UseIISIntegration()
	.UseStartup<Startup>()
	.Build();

I didn’t really like this approach as we’re hard-coding URLs. Fortunately it’s still possible to load the Kestrel configuration from an external file.

First create a hosting.json file in the root of your application with your required bindings. Separate multiple URLs with a semi-colon:

{
  "server.urls": "http://localhost:60000;http://localhost:60001"
}

Next update Program.cs to load your hosting configuration, then use the UseConfiguration extension to pass the configuration to the WebHostBuilder:

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", optional: true)
        .Build();

    var host = new WebHostBuilder()
        .UseKestrel()
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

If you’re launching Kestrel with Visual Studio you may also need to update launchSettings.json with the correct launchUrl:

"RC2HostingDemo": {
  "commandName": "Project",
  "launchBrowser": true,
  "launchUrl": "http://localhost:60000/api/values",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development"
  }
}

Now the web application will listen on the URLs configured in hosting.json:

Hosting environment: Development
Content root path: C:\Users\ben\Source\RC2HostingDemo\src\RC2HostingDemo
Now listening on: http://localhost:60000
Now listening on: http://localhost:60001
Application started. Press Ctrl+C to shut down.

© 2022 Ben Foster