Lesson Monday

Over the next few days, we'll build an application that will make calls to the API we built in the first part of this section. In order to do this, we'll need to have two applications running simultaneously. However, if we try running two applications on the same port, we'll get the following error:

Unhandled Exception: System.IO.IOException: Failed to bind to address https://127.0.0.1:5001: address already in use. ---> Microsoft.AspNetCore.Connections.AddressInUseException: Address already in use ---> System.Net.Sockets.SocketException: Address already in use

Fortunately, this is easy to fix. We just need to specify a different port number for one of the applications we are running.

There are many ways to do this. We'll list two simple configurations here:

When we scaffold an application, MVC will create a Properties/launchSettings.json file with a number of configurations, including the ones below:

Properties/launchSettings.json
"project_name_here": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }

For our application to listen on a different port, we can update the "applicationUrl" to specify different ports such as "https://localhost:5003;http://localhost:5004".

Alternatively, we can update our Program.cs file to include webBuilder.UseUrls. Then we specify the port number that we'd like to use.

Program.cs
...
  public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
          .ConfigureWebHostDefaults(webBuilder =>
          {
              webBuilder.UseStartup<Startup>();
              webBuilder.UseUrls("http://localhost:5004/");
          });

Lesson 15 of 21
Last updated more than 3 months ago.