asp.net core 2 web api从appsettings设置托管网址

时间:2018-02-16 16:19:42

标签: c# asp.net-core kestrel-http-server

在asp.net core 2 web api上,我希望能够根据appsettings.json文件中的值设置我的api将监听的URL(api作为windows服务运行)。我无法找到实现它的方法,如何访问IConfiguration的实例?

var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);

return WebHost.CreateDefaultBuilder(args)
    .UseContentRoot(pathToContentRoot)
    .UseStartup<Startup>()
    .UseUrls({value_from_appsettings})
    .Build()
    .RunAsService();

1 个答案:

答案 0 :(得分:2)

为了在之前访问配置,您沿着WebHost.CreateDefaultBuilder路径前进,您需要使用{{1}构建自己的IConfiguration实例}}

以您的问题为例,您可以使用以下内容:

ConfigurationBuilder

这在docs中有所解释,其中示例使用var pathToExe = Process.GetCurrentProcess().MainModule.FileName; var pathToContentRoot = Path.GetDirectoryName(pathToExe); var appSettingsConfiguration = new ConfigurationBuilder() .SetBasePath(pathToContentRoot) .AddJsonFile("appsettings.json") .Build(); return WebHost.CreateDefaultBuilder(args) .UseContentRoot(pathToContentRoot) .UseStartup<Startup>() .UseUrls(appSettingsConfiguration["Your:Value"]) .Build() .RunAsService(); 文件来设置它。它还使用了hosting.json,它允许您指定一个值,例如: UseConfiguration,将自动获取。