433

When using WebHostBuilder in a Main entry-point, how can I specify the port it binds to?

By default it uses 5000.

Note that this question is specific to the new ASP.NET Core API (currently in 1.0.0-RC2).

5
  • 17
    examine launchSettings.json from Properties folder. You can change the port in the launchUrl.
    – Oleg
    CommentedMay 21, 2016 at 16:20
  • @Oleg, I had some IIS related settings in there left over from RC1's project template. They didn't have any effect.CommentedMay 21, 2016 at 16:24
  • One can use hosting.json (see the answer), which were used by default in RC1 and one need just add .AddJsonFile("hosting.json", optional: true) (see here)
    – Oleg
    CommentedMay 21, 2016 at 16:30
  • 3
    Using the configuration stack seems indeed much better than relying on a purely VS-specific mechanism (launchSettings.json).CommentedMay 21, 2016 at 16:34
  • @DrewNoakes: I appended my old answer with UPDATED 2 part. It describes some variation of changing the default port and usage of hosting.json or the command line for configuring of the binding.
    – Oleg
    CommentedMay 21, 2016 at 22:41

14 Answers 14

659

In ASP.NET Core 3.1, there are four main ways to specify a custom port:

  • Using command line arguments, by starting your .NET application with --urls=[url]:

    dotnet run --urls=http://localhost:5001/ 
  • Using appsettings.json, by adding a Urls node:

    { "Urls": "http://localhost:5001" } 
  • Using environment variables, with ASPNETCORE_URLS=http://localhost:5001/.

  • Using UseUrls(), if you prefer doing it programmatically:

    public static class Program { public static void Main(string[] args) => CreateHostBuilder(args).Build().Run(); public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(builder => { builder.UseStartup<Startup>(); builder.UseUrls("http://localhost:5001/"); }); } 

Or, if you're still using the web host builder instead of the generic host builder:

public class Program { public static void Main(string[] args) => new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseUrls("http://localhost:5001/") .Build() .Run(); } 
14
  • 76
    The usage of fixed URLs directly in the code is not the best choice in my opinion.
    – Oleg
    CommentedMay 21, 2016 at 16:24
  • 4
    Tested this and it works well, thanks. @Oleg, could you flesh out an answer showing what config you need? It might be good to have this in a config file.CommentedMay 21, 2016 at 16:27
  • 7
    @Oleg maybe, but using UseUrls is the approach recommended by the ASP.NET team for self-hosting scenarios (the value itself doesn't have to be hardcoded, obviously). That said, I updated my answer to mention how you could do that using the configuration builder.CommentedMay 21, 2016 at 16:32
  • 2
    @Pinpoint: I posted the old answer, where one can find how to change the port using hosting.json. The only thing, which one have to do is forcing reading the information in RC2 (see the announcement).
    – Oleg
    CommentedMay 21, 2016 at 16:37
  • 3
    You'll need the following package: using Microsoft.Extensions.Configuration.CommandLine;
    – Learner
    CommentedMay 3, 2018 at 7:08
156

You can insert Kestrel section in asp.net core 2.1+ appsettings.json file.

 "Kestrel": { "EndPoints": { "Http": { "Url": "http://0.0.0.0:5002" } } }, 

if you do not have kestrel section, you can use "urls":

{ "urls":"http://*.6001;https://*.6002" } 

but if you have kestrel in appsettings.json, urls section will failure.

7
89

Follow up answer to help anyone doing this with the VS docker integration. I needed to change to port 8080 to run using the "flexible" environment in google appengine.

You'll need the following in your Dockerfile:

ENV ASPNETCORE_URLS=http://+:8080 EXPOSE 8080 

and you'll need to modify the port in docker-compose.yml as well:

 ports: - "8080" 
4
  • 4
    Thanks, we can set variables in windows command promt the same way: set ASPNETCORE_URLS=http://*:8080CommentedMar 12, 2018 at 10:40
  • 2
    this isn't working for me. are you sure this is all that you modified? Did you need to do anything special to your image afterwords or anything with docker?
    – Steve
    CommentedMay 23, 2018 at 1:32
  • It's been so long that it may have changed, but if I recall that was all I needed to do.
    – Casey
    CommentedMay 24, 2018 at 3:38
  • in VS Code, you can add that "ASPNETCORE_URLS": "http://+:8080" on "env" section of launch.json, to override other settings.
    – gorlok
    CommentedMar 13, 2019 at 13:25
47

You can specify hosting URL without any changes to your app.

Create a Properties/launchSettings.json file in your project directory and fill it with something like this:

{ "profiles": { "MyApp1-Dev": { "commandName": "Project", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "http://localhost:5001/" } } } 

dotnet run command should pick your launchSettings.json file and will display it in the console:

C:\ProjectPath [master ≡] λ dotnet run Using launch settings from C:\ProjectPath\Properties\launchSettings.json... Hosting environment: Development Content root path: C:\ProjectPath Now listening on: http://localhost:5001 Application started. Press Ctrl+C to shut down. 

More details: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments

3
  • 1
    Work in the appSettings.json too?
    – Paulo
    CommentedJan 12, 2019 at 12:59
  • No, it has to be in [ProjectRoot]/Properties/launchSettings.json, but the beautiful thing is, it works without a hitch.CommentedJan 20, 2019 at 3:43
  • 11
    This is only useful during development, does not work with binaries. in order to use dotnet run you need access to the source code.
    – rsenna
    CommentedApr 9, 2019 at 14:08
44

Above .net core 2.2 the method Main support args with WebHost.CreateDefaultBuilder(args)

public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } 

You can build your project and go to bin run command like this

dotnet <yours>.dll --urls=http://0.0.0.0:5001 

or with multi-urls

dotnet <yours>.dll --urls="http://0.0.0.0:5001;https://0.0.0.0:5002" 

Edit 2021/09/14

After .net core 3.1 you can change the file appsettings.json in the project, Config section Urls and Kestrel all works. And you can use either. Urls will easier.

{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "MicrosoftHostingLifetime": "Information" } }, "Urls": "http://0.0.0.0:5002", //"Kestrel": { // "EndPoints": { // "Http": { // "Url": "http://0.0.0.0:5000" // }, // "Https": { // "Url": "https://0.0.0.0:5001" // } // } //}, "AllowedHosts": "*" } 

Use http://0.0.0.0:5000 can access the webserver from remote connect, If you set to http://localhost:5000 that will access only in your computer.

To make Kestrel setting works, you shoud change code in Program.cs in the project.

 public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureServices((context, services) => { services.Configure<Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions>(context.Configuration.GetSection("Kestrel")); }); webBuilder.UseStartup<Startup>(); }); 
2
  • 3
    you can simple to use 'dotnet run --urls=0.0.0.0:5001' in project directory
    – oudi
    CommentedJan 17, 2020 at 6:31
  • This answer worked for me. For the multi-url case, I had to change the comma , to a semi-colon like this: --urls="http://localhost:5001;https://localhost:5002". Otherwise, had an error starting Kestrel: System.InvalidOperationException: A path base can only be configured using IApplicationBuilder.UsePathBase().CommentedSep 13, 2021 at 15:36
35

Alternative solution is to use a hosting.json in the root of the project.

{ "urls": "http://localhost:60000" } 

And then in Program.cs

public static void Main(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("hosting.json", true) .Build(); var host = new WebHostBuilder() .UseKestrel(options => options.AddServerHeader = false) .UseConfiguration(config) .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } 
2
  • 7
    This didn't work for me. server.urls is now urls and make sure you add entry to project.json "publishOptions": { "include": [ "appsettings.json", "web.config", "wwwroot", "hosting.json" ] },CommentedDec 14, 2016 at 18:54
  • 3
    I updated his answer with the correct property urls - thanks @ManishJain
    – TetraDev
    CommentedAug 29, 2017 at 23:33
32

If using dotnet run

dotnet run --urls="http://localhost:5001" 
1
  • 6
    The perfect answer! Works in docker. Replaced only "localhost" with "0.0.0.0"
    – AndrewPt
    CommentedJan 30, 2020 at 13:50
16

When hosted in docker containers (linux version for me), you might get a 'Connection Refused' message. In that case you can use IP address 0.0.0.0 which means "all IP addresses on this machine" instead of the localhost loopback to fix the port forwarding.

public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseUrls("http://0.0.0.0:5000/") .Build(); host.Run(); } } 
    13

    On .Net Core 3.1 just follow Microsoft Doc that it is pretty simple: kestrel-aspnetcore-3.1

    To summarize:

    1. Add the below ConfigureServices section to CreateDefaultBuilder on Program.cs:

      // using Microsoft.Extensions.DependencyInjection; public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.Configure<KestrelServerOptions>( context.Configuration.GetSection("Kestrel")); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); 
    2. Add the below basic config to appsettings.json file (more config options on Microsoft article):

      "Kestrel": { "EndPoints": { "Http": { "Url": "http://0.0.0.0:5002" } } } 
    3. Open CMD or Console on your project Publish/Debug/Release binaries folder and run:

      dotnet YourProject.dll 
    4. Enjoy exploring your site/api at your http://localhost:5002

      6

      Go to properties/launchSettings.json and find your appname and under this, find applicationUrl. you will see, it is running localhost:5000, change it to whatever you want. and then run dotnet run...... hurrah

        6

        Alternatively, you can specify port by running app via command line.

        Simply run command:

        dotnet run --server.urls http://localhost:5001 

        Note: Where 5001 is the port you want to run on.

          4

          I found this question relating to .Net Core 3.1 but try to do it with .Net 6. So the first two options still work, but the programatical way has changed. (And that was what I needed).

          So with .Net 6 you can use command line arguments:

          dotnet run --urls=http://localhost:5001/

          Using appsettings.json:

          { "Urls": "http://*:14071" } 

          Programmatically you should now:

          var builder = WebApplication.CreateBuilder(options); //... builder.WebHost.UseUrls("http://localhost:14071"); 

          Update

          It is also possible to use ConfigureKestrel with server options to define the Port. What gives you the option to define more details for Kestrel Options.

          builder.WebHost.ConfigureKestrel(serverOptions => { serverOptions.ListenAnyIP(14072); }); 

          or

          var ipEndpoint = new IPEndPoint(IPAddress.Any, 14072); builder.WebHost.ConfigureKestrel(serverOptions => { serverOptions.Listen(ipEndpoint, listenOptions => { listenOptions.UseHttps("Your.pfx"); listenOptions.Use(async (context, next) => { // Your Middleware for e.g. logging }); }); 
            1

            I fixed the port issue in Net core 3.1 by using the following

            In the Program.cs

            public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHost(x => x.UseUrls("https://localhost:4000", "http://localhost:4001")) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } 

            You can access the application using

            http://localhost:4000 https://localhost:4001 
            1
            • 1
              This gets completely ignored. Still listens on another port (no idea where that is specified(.CommentedJan 25, 2021 at 15:13
            0

            Solved multiple ports for angular with the server side dotnet cli using the --urls like this:

            dotnet run --urls="https://localhost:7203;http://localhost:5001;" 

            The order matters.

            1
            • Consider wrapping the command in a code block, to make it more visible. Thanks.
              – aolsan
              CommentedFeb 12 at 12:16

            Start asking to get answers

            Find the answer to your question by asking.

            Ask question

            Explore related questions

            See similar questions with these tags.