ASP.NET Core environment variable from Azure

Viewed 72

I'm working with .NET Core 6.0, my app is deployed to Azure.

I want to get access to environment variables in Azure from my code.

I created the key value in Azure:

enter image description here

When I try to access it using this code snippet:

Environment.GetEnvironmentVariable("BROKER_IP")

or

_conf["BROKER_IP"])

(IConfiguration is injected in the constructor), it is working when i run the program locally(able to get environment variable from my local PC), but when deployed to Azure (as an App Service), it doesn't return any value.

How can I access it from my API?

Part of my program.cs looks like this:

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

I added this line :

builder.Configuration.AddEnvironmentVariables();

but I still have the same issue.

Thank you

1 Answers

You just need to inject IConfiguration to your controller. I don't change any code in Startup.cs or Program.cs file. And it works for me.

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);
    }
}

Test Result

enter image description here

enter image description here

Related