2
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!

poke
  • 369,085
  • 72
  • 557
  • 602
user584018
  • 10,186
  • 15
  • 74
  • 160

2 Answers2

5

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();
poke
  • 369,085
  • 72
  • 557
  • 602
2

This should work:

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();
    }
}
citronas
  • 19,035
  • 27
  • 96
  • 164
  • 3
    Creating yet another configuration that you need to set up (and keep in sync if you have different sources, like environment-specific configurations) is really not needed with the generic host. – poke Apr 19 '20 at 12:17
  • 1
    @poke Oh cool, I didn't know about `webBuilder.ConfigureServices((context, services)`. Glad I learned something on a Sunday ;) – citronas Apr 19 '20 at 13:06
  • 1
    You just finaly saved me from hours of searching :) thank you – Roger Jun 23 '21 at 08:33