Search code examples
c#asp.net-corehttpsys

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

appsettings config,

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

Looks like I can use hostingContext.Configuration, but it won't available within UseHttpSys, how to do this? Thanks!


Solution

  • IWebHostBuilder.UseHttpSys(Action) consists of two parts: Registering the required services, and configuring the HttpSysOptions. You can split this up by registering only the required services and configuring the options yourself. And when you do that, you can access the hosting context:

    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();