ChatGPT解决这个技术问题 Extra ChatGPT

How to specify the port an ASP.NET Core application is hosted on?

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

examine launchSettings.json from Properties folder. You can change the port in the launchUrl.
@Oleg, I had some IIS related settings in there left over from RC1's project template. They didn't have any effect.
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)
Using the configuration stack seems indeed much better than relying on a purely VS-specific mechanism (launchSettings.json).
@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.

K
Kévin Chalet

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();
}

The usage of fixed URLs directly in the code is not the best choice in my opinion.
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.
@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.
@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).
You'll need the following package: using Microsoft.Extensions.Configuration.CommandLine;
m
menxin

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.


Thank you, just what I needed :-) Better than UseUrls(). More details: docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/…
THIS actually works with binaries generated through dotnet publish.
Isn't this defining the port Kestrel is binded to IIS (proxy) rather than the port the app is hosted on in IIS?
@user12345 In IIS hosting,Kestrel use dynamic port binding.
also works with netcore 3.0 running web api from exe, briliant!!!
C
Casey

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"

Thanks, we can set variables in windows command promt the same way: set ASPNETCORE_URLS=http://*:8080
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?
It's been so long that it may have changed, but if I recall that was all I needed to do.
in VS Code, you can add that "ASPNETCORE_URLS": "http://+:8080" on "env" section of launch.json, to override other settings.
D
Drew Noakes

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://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments


Work in the appSettings.json too?
No, it has to be in [ProjectRoot]/Properties/launchSettings.json, but the beautiful thing is, it works without a hitch.
This is only useful during development, does not work with binaries. in order to use dotnet run you need access to the source code.
T
TetraDev

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();
}

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" ] },
I updated his answer with the correct property urls - thanks @ManishJain
j
jabu.hlong

If using dotnet run

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

The perfect answer! Works in docker. Replaced only "localhost" with "0.0.0.0"
o
oudi

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>();
            });

you can simple to use 'dotnet run --urls=0.0.0.0:5001' in project directory
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().
R
R. van Diesen

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();
    }
}

B
Burak Kalafat

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

To summarize:

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( context.Configuration.GetSection("Kestrel")); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); 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" } } } Open CMD or Console on your project Publish/Debug/Release binaries folder and run: dotnet YourProject.dll Enjoy exploring your site/api at your http://localhost:5002


M
Mwiza

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.


M
Md Rafee

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


S
Sukesh Chand

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

This gets completely ignored. Still listens on another port (no idea where that is specified(.