How to configure Kestrel URLs in ASP.NET Core RC2

Posted by Anuraj on Thursday, June 23, 2016

C# ASP.NET ASP.NET Core Kestrel

This post is to about configuring Kestrel URLs. Prior RC2, you can configure the Kestrel URLs in the project.json using –server.urls option, inside the Web command section. And if nothing specified, it will use the default binding http://localhost:5000. 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, commands are no more relevant. You can modify the main method to change the URLs using the UseUrls method.

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
                .UseUrls("http://localhost:5010", "http://localhost:5012")
                .UseIISIntegration()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .Build();
    host.Run();
}

But I am not a fan of hard coding the URLs. Fortunately it’s still possible to load the Kestrel configuration from an external file. Create hosting.json file in the root directory, and add the URLs inside it like this.

{
  "server.urls": "http://localhost:5010;http://localhost:5012"
}

And you can load the configuration using AddJsonFile method, and apply it using the UseConfiguration method.

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", optional: true)
        .Build();
        
    var host = new WebHostBuilder()
        .UseConfiguration(config)
        .UseIISIntegration()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .Build();
    host.Run();
}

Similar way you can configure the URLs from command line as well as Environment variables.

var config = new ConfigurationBuilder()
    .AddJsonFile("hosting.json", optional: true)
    .AddCommandLine(args)
    .AddEnvironmentVariables(prefix: "ASPNETCORE_")
    .Build();

And to use the ConfigurationBuilder class, you require “Microsoft.Extensions.Configuration” reference in the project.json file.

Happy Programming :)


Similar Posts


Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



MVP
Subscribe


Copyright © 2017 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub