Kestrel 配置侦听地址

使用 Kestrel,你可以使用下一种方法指定端口:

  1. 定义 ASPNETCORE_URLS 环境变量。

    视窗

    SET ASPNETCORE_URLS=https://0.0.0.0:5001
    

    OS X.

    export ASPNETCORE_URLS=https://0.0.0.0:5001
    
  2. 通过命令行传递 --server.urls 参数

    dotnet run --server.urls=http://0.0.0.0:5001
    
  3. 使用 UseUrls() 方法

    var builder = new WebHostBuilder()
                  .UseKestrel()
                  .UseUrls("http://0.0.0.0:5001")
    
  4. 在配置源中定义 server.urls 设置。

下一个示例使用 hosting.json 文件。

Add `hosting.json` with the following content to you project:

    {
       "server.urls": "http://<ip address>:<port>" 
    }

可能值的例子:

  • 从任何接口侦听任何 IP4 和 IP6 地址 5000:

     "server.urls": "http://*:5000" 
    

    要么

     "server.urls": "http://::5000;http://0.0.0.0:5000"
    
  • 在每个 IP4 地址上听 5000:

     "server.urls": "http://0.0.0.0:5000"
    

一个应该小心,不要使用 http://*:5000;http://::5000http://::5000;http://*:5000http://*:5000;http://0.0.0.0:5000http://*:5000;http://0.0.0.0:5000,因为它需要两次注册 IP6 地址::或 IP4 地址 0.0.0.0

project.json 中添加文件到 publishOptions

"publishOptions": {
"include": [
    "hosting.json",
    ...
  ]
}

并在创建 WebHostBuilder 时应用程序调用 .UseConfiguration(config) 的入口点:

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", optional: true)
        .Build();

    var host = new WebHostBuilder()
        .UseConfiguration(config)
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}