13

In ASP.NET Core, if reading configuration from a JSON app.settings file I can bind a section to an object like this:

services.Configure<MyPocoConfig>(Configuration.GetSection("Section"))

Is there a straightforward way to do this with a group of settings that are read from Azure Key Vault? I am following the guide as described in the MSDN documentation here https://learn.microsoft.com/en-us/azure/key-vault/vs-key-vault-add-connected-service#access-your-secrets-in-code

I can manually map them like this:

services.Configure<MyPocoConfig>(myPoco =>
                {
                    myPoco.Option1 = Configuration["Option1"];
                    myPoco.Option2 = Configuration["Option2"];
                });

I just wondered if there was a way to automap them as it works for config stored in app.settings JSON. I'm sure it could be done with reflection but I was hoping there'd be a built in way.

I tried putting the settings into a category using the category--setting syntax described in the article and reading them with services.Configure<MyPocoConfig>(Configuration.GetSection("category")), but this doesn't work.

Edit:

It is now possible as of 2020 to put settings into a category using the category--setting syntax and read them like services.Configure<MyPocoConfig>(Configuration.GetSection("category"))

zola25
  • 1,774
  • 6
  • 24
  • 44
  • What the meaning of `do this with a group of setting that read from azure key vault`? Could you give me more details about your idea? – Joey Cai Mar 18 '19 at 05:52
  • I've updated the question – zola25 Mar 19 '19 at 14:31
  • 1
    We were really surprised to find that there doesn't seem to be a way to do this. It seems that the Azure Key Vault provider would support binding via GetSection calls as well as ConnectionString sections. It seems so natural just do drop the config you have into a secret and use the provider to access it. Unfortunately that doesn't seem to be supported but hoping you get an answer on this! – xinunix Apr 18 '19 at 21:47

1 Answers1

11

You can achieve the same by naming your Secret in the following pattern.

 Section--Option1
 Section--Option2

And you can use the following to get the values by section and .NetCore automatically maps it.

services.Configure<MyPocoConfig>(Configuration.GetSection("Section"))

Refer link https://learn.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-2.2#bind-an-array-to-a-class

Naveen R Kumar
  • 636
  • 7
  • 7
  • It seems they've now added this functionality, which didn't work at the time the question was asked. Great stuff. – zola25 Oct 07 '20 at 18:19