您必须在main方法中构建配置,获取该部分并将其绑定到您的模型.没办法解决它.
public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false) .Build(); WebProtocolSettings settings_Web = new WebProtocolSettings(); config.GetSection("WebProtocolSettings").Bind(settings_Web); var host = new WebHostBuilder() .UseIISIntegration() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup() .UseUrls(settings_Web.Url + ":" + settings_Web.Port) .Build() host.Run(); }
另一种方法是将配置传递给UseConfiguration
如下所述
public static void Main(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("hosting.json", optional: true) .AddCommandLine(args) .Build(); var host = new WebHostBuilder() .UseUrls("http://*:5000") .UseConfiguration(config) .UseKestrel() .Configure(app => { app.Run(context => context.Response.WriteAsync("Hello, World!")); }) .Build(); host.Run(); }
或者在ASP.NET Core> 2.0中
public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("hosting.json", optional: true) .AddCommandLine(args) .Build(); return WebHost.CreateDefaultBuilder(args) .UseUrls("http://*:5000") .UseConfiguration(config) .Configure(app => { app.Run(context => context.Response.WriteAsync("Hello, World!")); }) .Build(); }