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,怎么办?谢谢!

4

2 回答 2

4

IWebHostBuilder.UseHttpSys(Action)由两部分组成:注册所需的服务和配置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();
于 2020-04-19T12:15:41.817 回答
2

这应该有效:

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();
    }
}
于 2020-04-19T12:14:37.960 回答