377

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).

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • 16
    examine `launchSettings.json` from `Properties` folder. You can change the port in the `launchUrl`. – Oleg May 21 '16 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. – Drew Noakes May 21 '16 at 16:24
  • One can use `hosting.json` (see [the answer](http://stackoverflow.com/a/34221690/315935)), which were used by default in RC1 and one need just add `.AddJsonFile("hosting.json", optional: true)` (see [here](https://github.com/aspnet/Announcements/issues/174)) – Oleg May 21 '16 at 16:30
  • 3
    Using the configuration stack seems indeed much better than relying on a purely VS-specific mechanism (launchSettings.json). – Kévin Chalet May 21 '16 at 16:34
  • @DrewNoakes: I appended [my old answer](http://stackoverflow.com/a/34221690/315935) 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 May 21 '16 at 22:41

12 Answers12

586

In ASP.NET Core 3.1, there are 4 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();
}
Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131
  • 69
    The usage of fixed URLs directly in the code is not the best choice in my opinion. – Oleg May 21 '16 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. – Drew Noakes May 21 '16 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. – Kévin Chalet May 21 '16 at 16:32
  • 2
    @Pinpoint: I posted [the old answer](http://stackoverflow.com/a/34221690/315935), 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](https://github.com/aspnet/Announcements/issues/174)). – Oleg May 21 '16 at 16:37
  • @Oleg I guess it would be worth updating your answer to add a tiny snippet showing what's needed to make it work with RC2 ;) – Kévin Chalet May 21 '16 at 16:39
  • @Pinpoint: The problem exist not with ASP.NET Core only. It's difficult to go over all old answers and to update there after publishing of every new version. :-) – Oleg May 21 '16 at 16:42
  • @Oleg agreed. Personally, I spent 1 hour yesterday to update all my ASP.NET Core security-related questions. I know how painful it can be :) – Kévin Chalet May 21 '16 at 16:43
  • @Pinpoint: It's very good if you can to do this, but I posted more as 5000 answers. It would take to many time... – Oleg May 21 '16 at 16:47
  • @Oleg luckily, all your answers are not about ASP.NET Core, so you won't have to update ~5000 posts :) And nothing prevents you from marking your answers as "community wiki posts" to let the community update your posts when needed. That said, I think we're now a bit off-topic :) – Kévin Chalet May 21 '16 at 16:52
  • @Pinpoint: I appended [my old answer](http://stackoverflow.com/a/34221690/315935) with **UPDATED 2** part. – Oleg May 21 '16 at 22:39
  • 3
    You'll need the following package: `using Microsoft.Extensions.Configuration.CommandLine;` – Learner May 03 '18 at 07:08
  • 2
    The post should be updated... dotnet run --urls=http://localhost:5001/ is what you need to use. – Stefan Ahlm Oct 11 '18 at 08:04
  • 2
    Hardcoding "localhost" either in `dotnet run` or in `UseUrls` is a bad idea because once this code makes it off the dev's machine any requests that don't contain localhost will get rejected. This caused me much pain in Kubernetes. Instead use the string like `http://*:5001`. – Lee Richardson May 05 '20 at 13:25
  • 1
    @ReiMiyasaka Once it is in the code you need to recompile the code to change the urls. Keeping it in a configuration file or environment variable allows to use the same build in different environments. The bigger the application the more important this becomes due to possibly long build times. – itmuckel Sep 23 '20 at 11:17
140

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 have not kestrel section,you can use "urls":

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

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

menxin
  • 2,044
  • 1
  • 17
  • 15
  • 6
    Thank you, just what I needed :-) Better than UseUrls(). More details: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-2.2 – KTCO Mar 22 '19 at 17:52
  • 14
    THIS actually works with binaries generated through `dotnet publish`. – rsenna Apr 09 '19 at 14:12
  • Isn't this defining [the port Kestrel is binded to IIS (proxy)](https://stackoverflow.com/questions/49871318/determine-port-kestrel-binded-to) rather than the port the app is hosted on in IIS? – michal krzych Apr 29 '19 at 13:47
  • @user12345 In IIS hosting,Kestrel use dynamic port binding. – menxin Apr 30 '19 at 09:17
  • 2
    also works with netcore 3.0 running web api from exe, briliant!!! – vidriduch Dec 03 '19 at 15:55
  • This can also be set with an environment variable `export Kestrel__EndPoints__Http__Url=http://0.0.0.0:80` – ATOMP Feb 22 '21 at 17:14
  • This works, but Swagger doesn't launch anymore. :( – FDM Feb 24 '22 at 20:48
79

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"
Casey
  • 1,573
  • 14
  • 17
  • 4
    Thanks, we can set variables in windows command promt the same way: set ASPNETCORE_URLS=http://*:8080 – Pavel Biryukov Mar 12 '18 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 May 23 '18 at 01:32
  • It's been so long that it may have changed, but if I recall that was all I needed to do. – Casey May 24 '18 at 03:38
  • in VS Code, you can add that "ASPNETCORE_URLS": "http://+:8080" on "env" section of launch.json, to override other settings. – gorlok Mar 13 '19 at 13:25
45

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

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Random
  • 4,519
  • 2
  • 38
  • 46
38

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>();
            });
oudi
  • 577
  • 4
  • 11
  • 3
    you can simple to use 'dotnet run --urls=http://0.0.0.0:5001' in project directory – oudi Jan 17 '20 at 06: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().` – Steve Wong Sep 13 '21 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();
}
TetraDev
  • 16,074
  • 6
  • 60
  • 61
Dennis
  • 20,275
  • 4
  • 64
  • 80
  • 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" ] }, – Manish Jain Dec 14 '16 at 18:54
  • 3
    I updated his answer with the correct property `urls` - thanks @ManishJain – TetraDev Aug 29 '17 at 23:33
31

If using dotnet run

dotnet run --urls="http://localhost:5001"
jabu.hlong
  • 2,194
  • 20
  • 21
15

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();
    }
}
R. van Diesen
  • 829
  • 8
  • 10
12

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

Burak Kalafat
  • 68
  • 2
  • 15
Ernest
  • 2,039
  • 24
  • 19
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

Md Rafee
  • 5,070
  • 3
  • 23
  • 32
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.

Mwiza
  • 7,780
  • 3
  • 46
  • 42
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
Sukesh Chand
  • 2,339
  • 2
  • 21
  • 29