在控制器中获取Azure AppSettings
我在Azure上托管了一个ASP.NET Core 2应用程序,并在Azure门户中为我的应用程序添加了一个新的应用程序设置在控制器中获取Azure AppSettings,azure,asp.net-core,application-settings,asp.net-core-2.0,azure-web-app-service,Azure,Asp.net Core,Application Settings,Asp.net Core 2.0,Azure Web App Service,我在Azure上托管了一个ASP.NET Core 2应用程序,并在Azure门户中为我的应用程序添加了一个新的应用程序设置MyNewSetting 如何从控制器访问该设置 我的代码如下: public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure<AppSecrets>(Configuration); servi
MyNewSetting
如何从控制器访问该设置
我的代码如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<AppSecrets>(Configuration);
services.AddSingleton<ITableRepositories, TableClientOperationsService>();
//...
在这里,我可能需要添加FromServices
注入,但我不确定它是否有效
编辑:
根据@dee_zg的答案,以下代码可能可以完成这项工作:
public class RecordController : Controller
{
int MyNewSetting = 7;
private readonly ITableRepositories repository;
public RecordController(ITableRepositories rep) {
repository = rep;
int myInt;
if (int.TryParse(System.Environment.GetEnvironmentVariable("MY_NEW_SETTING"),
out myInt)) {
MyNewSetting = myInt;
};
}
您可以选择从
AppSettings[“您的密钥”]
集合获取它们,也可以选择作为环境变量获取它们:environment.GetEnvironmentVariable(“您的密钥”)
从那里,您可以将它们映射到您的自定义IOption,并在任何需要它们的地方进行注入。您可以做很多事情
IOptionsSnapshot
支持在配置文件更改时重新加载配置数据。它的开销最小。将IOptionsSnapshot
与reloadOnChange:true
一起使用,选项将绑定到配置
,并在更改时重新加载
希望这能有所帮助。在提问之前,我已经看过了这些文档。说,我知道要用什么,我不知道如何使用,这就是为什么我添加了一些代码。谢谢。我不会问示例中的代码是否对我的案例有用。
public class RecordController : Controller
{
int MyNewSetting = 7;
private readonly ITableRepositories repository;
public RecordController(ITableRepositories rep) {
repository = rep;
int myInt;
if (int.TryParse(System.Environment.GetEnvironmentVariable("MY_NEW_SETTING"),
out myInt)) {
MyNewSetting = myInt;
};
}