如何从 program.cs - asp.net core 3.1 中的 appsettings 读取 UrlPrefixes

how to read UrlPrefixes from appsettings in program.cs - asp.net core 3.1

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseHttpSys(options =>
            {
                options.UrlPrefixes.Add("how to get url from appsettings");
            });
            webBuilder.UseStartup<Startup>();
        })
        //host as window service
        .UseWindowsService();
    }

应用设置配置,

"HttpSysOptions": {
    "UrlPrefix": "http://localhost:8099/"
}

看来我可以使用hostingContext.Configuration,但在UseHttpSys内将无法使用,怎么办?谢谢!

这应该有效:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: true)
        .Build();

    string urlPrefix = configuration.GetSection("HttpSysOptions")["UrlPrefix"];
    return Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseHttpSys(options =>
            {
                options.UrlPrefixes.Add(urlPrefix);
            });
            webBuilder.UseStartup<Startup>();
        })
        //host as window service
        .UseWindowsService();
    }
}

IWebHostBuilder.UseHttpSys(Action) consists of two parts: Registering the required services, and configuring the HttpSysOptions。您可以通过仅注册所需的服务并自行配置选项来拆分它。当您这样做时,您可以访问托管上下文:

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseHttpSys();
        webBuilder.ConfigureServices((context, services) =>
        {
            services.Configure<HttpSysOptions>(options =>
            {
                options.UrlPrefixes.Add(context.Configuration["HttpSysOptions:UrlPrefix"]);
            });
        });

        webBuilder.UseStartup<Startup>();
    })
    .UseWindowsService();