Search code examples
c#azure.net-7.0azure-app-configuration

Create/Update Azure App config through .NET 7 C# controller


I am trying to create (update if exists) Azure App Config values through .NET 7 C# controller.

The goal is basically send a key-value pair as json through my controller and let my backend process save that key-value pair to Azure App Config.

So the question is: can I send a key-value pair to Azure App Config through my C# code?

PS: I know it is possible through Azure CLI and Importing through portal :)


Solution

  • Can I send a key-value pair to Azure App Config through my c# code?

    Yes, you can send a key-value from Controller Action Method and create a key-value pair in Azure App Configuration.

    • As mentioned in the MSDoc, I have used SetConfigurationSetting to create a Key-Value pair.

    My appsettings.json file:

    "AppConfig": "Endpoint=https://harshuappconfig.azconfig.io;Id=RoKQ;Secret=****************"
    

    My Program.cs file:

    var appConfig = builder.Configuration["AppConfig"];
    builder.Services.AddAzureAppConfiguration();
    

    My Controller ActionMethod:

      private readonly IConfiguration config;
      private readonly ConfigurationClient configClient;
    
    public HomeController(IConfiguration myconfig, ILogger<HomeController> logger)
     {
         _logger = logger;
         config = myconfig;
         var connectionString = config["AppConfig"];
    
         configClient = new ConfigurationClient(connectionString);
     }
     public IActionResult Index()
     {
         var KVPair = JObject.Parse(@"{""Name"":""Harshitha"",""SurName"":""Veeramalla""}");
         foreach (var kv in KVPair)
         {
    
             Console.WriteLine($"Key '{kv.Key}' updated value '{kv.Value}' in Azure App Config.");
             var setting = new ConfigurationSetting(kv.Key, kv.Value.ToString());
             configClient.SetConfigurationSetting(setting);
         }
         return View();
     }
    
    • Here I am sending the JSON object in a string.

    Output: enter image description here

    enter image description here