Setting ASP.NET host address in .NET Core 2

 September 12, 2017


Why would I need to set the host address?

If you rely on default behavior, then port 5000 is used (running in VS+IIS Express will give a random port designated by VS). And, only one app. at a time can use the same port (on the same machine/interface). If a second app. is run, this error is thrown:

> dotnet run
crit: Microsoft.AspNetCore.Server.Kestrel[0]
      Unable to start Kestrel.
System.IO.IOException: Failed to bind to address http://127.0.0.1:5000: address already in use.
---> Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.AddressInUseException: Error -4091 EADDRINUSE address already in use
---> Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.UvException: Error-4091 EADDRINUSE address already in use

Two roads diverged... sort of 😉

Setting host address in the app.

If you already know what port your app. will consistenly use, it may make sense to just code this into your app with UseUrls:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;

namespace DotNetCore2Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()

                // params string[] urls
                .UseUrls(urls: "http://localhost:10000")

                .Build();
    }
}

✨ Setting host address via ConfigurationBuilder

If you want a bit more control to set the address via app. setting or command line, then construct a ConfigurationBuilder:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;

namespace DotNetCore2Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args)
        {
            var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: true)
                .AddCommandLine(args)
                .Build();

            return WebHost.CreateDefaultBuilder(args)
                .UseConfiguration(config)
                .UseStartup<Startup>()
                .Build();
        }
    }
}
> dotnet run --urls="http://localhost:10000"
Hosting environment: Production
Content root path: ...
Now listening on: http://localhost:15000
Application started. Press Ctrl+C to shut down.

Tech. tidbits

For those who are interested where the default stuff comes into play...

Read this if you want to compare how this stuff used to work.