gpt4 book ai didi

Azure 中的 ASP.NET Core 环境变量

转载 作者:行者123 更新时间:2023-12-02 07:32:44 25 4
gpt4 key购买 nike

我正在使用 .NET Core 6.0,我的应用程序已部署到 Azure。

我想从我的代码访问 Azure 中的环境变量。

我在 Azure 中创建了键值:

enter image description here

当我尝试使用以下代码片段访问它时:

Environment.GetEnvironmentVariable("BROKER_IP")

_conf["BROKER_IP"])

(IConfiguration 被注入(inject)到构造函数中),当我在本地运行程序时(能够从本地 PC 获取环境变量),但当部署到 Azure 时(作为应用程序服务),它可以正常工作),它不返回任何值。

如何从我的 API 访问它?

我的program.cs的一部分如下所示:

var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));

我添加了这一行:

builder.Configuration.AddEnvironmentVariables();

但我仍然遇到同样的问题。

谢谢

最佳答案

您只需将 IConfiguration 注入(inject)到您的 Controller 中。我没有更改 Startup.cs 或 Program.cs 文件中的任何代码。它对我有用。

public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IConfiguration _config;



public HomeController(ILogger<HomeController> logger, IConfiguration config)
{
_logger = logger;
_config = config;
}

public IActionResult Index()
{
//ViewData["aa"] = "Learn about";
return View();
}

[HttpGet("getKey")]
public IActionResult GetTestKey()
{
string aa = _config["testKey"] ==null ? "test in local" : _config["testKey"].ToString();
return Ok(aa);
}
}

测试结果

enter image description here

enter image description here

关于Azure 中的 ASP.NET Core 环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73757799/

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