当在主入口点使用WebHostBuilder时,我如何指定它绑定到的端口?

默认情况下,它使用5000。

请注意,这个问题是特定于新的ASP。NET Core API(目前在1.0.0-RC2中)。


当前回答

或者,你也可以通过命令行运行app来指定端口。

简单地运行命令:

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

注意:其中5001是要运行的端口。

其他回答

另一种解决方案是使用主机。Json在项目的根目录中。

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

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

进入properties/launchSettings。找到你的appname,在这个下面找到applicationUrl。您将看到,它正在运行localhost:5000,将其更改为您想要的任何名称。然后运行dotnet运行......好哇

你可以在asp.net core 2.1+ appsettings中插入Kestrel section。json文件。

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

如果你没有kestrel部分,你可以使用"urls":

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

但如果你在appsettings中有kestrel。Json, url部分将失败。

在ASP。NET Core 3.1,有4种主要的方法来指定一个自定义端口:

使用命令行参数,用——url =[url]启动你的.NET应用程序:

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

使用appsettings。通过添加一个url节点:

{
  "Urls": "http://localhost:5001"
}

使用环境变量,ASPNETCORE_URLS=http://localhost:5001/。 使用UseUrls(),如果你喜欢以编程方式完成:

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/");
            });
}

或者,如果你仍然在使用web主机生成器而不是通用的主机生成器:

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

或者,你也可以通过命令行运行app来指定端口。

简单地运行命令:

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

注意:其中5001是要运行的端口。