gpt4 book ai didi

azure - 在 Controller 中获取 Azure AppSettings

转载 作者:行者123 更新时间:2023-12-03 01:45:39 25 4
gpt4 key购买 nike

我在 Azure 上托管了一个 ASP.NET Core 2 应用程序,并且我在 Azure 门户中为我的应用程序添加了新的应用程序设置 MyNewSetting

如何从 Controller 访问该设置?

我的代码如下:

public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();

services.Configure<AppSecrets>(Configuration);
services.AddSingleton<ITableRepositories, TableClientOperationsService>();
//...

我的 Controller :

public class RecordController : Controller
{
const int MyNewSetting = 7; // this one to replace with Azure Setting one
private readonly ITableRepositories repository;

public RecordController(ITableRepositories rep) {
repository = rep;
}

在这里,我可能需要添加 FromServices 注入(inject),但我不确定它是否会起作用......

编辑:

根据@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["your-key"] 集合中获取它们,也可以将其作为环境变量:Environment.GetEnvironmentVariable("your-key")

从那里您可以将它们映射到您的自定义 IOptions 并在需要的地方注入(inject)。

关于azure - 在 Controller 中获取 Azure AppSettings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47032896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com