如何在 Kestrel 中配置端点?

How can I configure endpoints in Kestrel?

我正在学习如何在 ASP.NET 核心 2 中工作,我遇到了一个相当烦人的问题。每当我 运行 我的应用程序时,Kestrel 服务器都会忽略我的端点配置,而是开始侦听随机端口。不用说,这不是我所期望的行为。在挖掘服务器日志时,我还发现了这条消息:

Overriding endpoints defined in UseKestrel() because PreferHostingUrls is set to true. Binding to address(es) 'http://localhost:<some random port>' instead.

到目前为止,我找不到关于此 "PreferHostingUrls" 设置或如何更改它的任何文档。有谁知道我如何配置 Kestrel 以侦听指定端口而不是随机端口?

我的主机配置如下所示:

WebHost.CreateDefaultBuilder(args)
        .UseConfiguration(config)
        .UseKestrel(
            options =>
            {
                options.Listen(IPAddress.Loopback, 50734);
                options.Listen(IPAddress.Loopback, 44321, listenOptions =>
                {
                    listenOptions.UseHttps("pidea-dev-certificate.pfx", "****************");
                });
            })
        .UseStartup<Startup>()
        .UseIISIntegration()
        .Build();

好的,原来 IISExpress 是罪魁祸首。

出于某种原因,Visual Studio 2017 的默认构建配置在 IISExpress 服务器上启动我的应用程序,该服务器不监听我的端点配置。为了解决这个问题,我只需要切换到自定义 运行 配置。

总而言之,我只需要从这里切换:

对此:

(PIdea 是我项目的名称)

添加

"Kestrel": {
  "EndPoints": {
    "Http": {
      "Url": "http://localhost:5002"
    },
    "Https": {
      "Url": "https://localhost:5003"
    }
  }
}  

appsettings.json

当我使用 .NetCore 3.0 进行测试时,我在 launchSettings.json
中使用不同的端口 5000 失败 这是文件 launchSettings.json

中的设置
"ABC": {
   "commandName": "Project",
   "launchBrowser": true,
   "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development"
    },
    "applicationUrl": "http://localhost:5002"
 }

我认为这是 默认主机使用端口 5000 运行的根本原因 当有变化时,需要修改设置。

有 3 种方法可以达到预期效果:

  1. appsettings.jsonappsettings.Development.json

    中添加kestrel设置
    "Kestrel": {
      "EndPoints": {
        "Http": {
          "Url": "http://localhost:5002"
        },
        "Https": {
          "Url": "https://localhost:5003"
        }
      }
    },
    
  2. 使用注册监听不同端口的Kestrel

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args).ConfigureKestrel(serverOptions =>
        {
            // Set properties and call methods on options
            serverOptions.Listen(IPAddress.Loopback, 5002); //Modify port
        })
       .UseKestrel()
       .UseContentRoot(Directory.GetCurrentDirectory())  
       .UseIISIntegration()
       .UseStartup<Startup>();
    

    或修改appsettings.json中的配置。

    "Host": {  
      "Port": 5002  
    } 
    

    然后像下面这样调用

    .ConfigureKestrel(serverOptions =>
        {
            // Set properties and call methods on options
            options.Listen(IPAddress.Loopback, config.GetValue<int>("Host:Port"));
        })
    

    .UseKestrel((context, serverOptions) =>
        {  
            var config = new ConfigurationBuilder()  
               .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", optional: false).Build();  
            options.Listen(IPAddress.Loopback, context.Configuration.GetValue<int>("Host:Port"));  
         }) 
    

    或在Startup.ConfigureServices中,将配置的 Kestrel 部分加载到 Kestrel 的配置中:

     public void ConfigureServices(IServiceCollection services)
     {
          services.Configure<KestrelServerOptions>(
              Configuration.GetSection("Kestrel"));
     }
    
  3. 使用UseUrls

     public class Program
     {      
         public static void Main(string[] args)
         {
             CreateHostBuilder(args).Build().Run();
         }
    
         public static IHostBuilder CreateHostBuilder(string[] args) =>
             Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(builder =>
             {
                 builder.ConfigureKestrel(serverOptions =>
                     {
                         // Set properties and call methods on options
                     })
                     .UseContentRoot(Directory.GetCurrentDirectory())
                     .UseIISIntegration()
                     .UseUrls("http://localhost:5002")  //Add UseUrl above UseStartup
                     .UseStartup<Startup>();
             });     
          }
      }
    

     public static IWebHostBuilder CreateWebHostBuilder(string[] args)  
     {  
         var config = new ConfigurationBuilder()  
             .SetBasePath(Directory.GetCurrentDirectory())  
             .AddJsonFile("appsettings.json", optional: false)  
             .Build();  
    
         var webHost =  WebHost.CreateDefaultBuilder(args)  
             .UseUrls($"http://localhost:{config.GetValue<int>("Host:Port")}")  
             .UseKestrel()  
             .UseStartup<Startup>();  
    
         return webHost;  
     }