Custom Section / Collection in Web.Config

I have a bunch of routes that I want to get in my Web.Config file. I need one key and two value fields for each section / element in the collection. Something like that...

<routes> <add key="AdministrationDefault" url="Administration/" file="~Administration/Default.aspx" /> <add key="AdministrationCreateCampaign" url="Administration/CreateCampaign/" file="~/Administration/CreateCampaign.aspx" /> <add key="AdministrationLogout" url="Administration/Leave/" file="~/Administration/Leave.aspx" /> </routes> 

Is it possible?

+6
source share
3 answers

Yes. And not too hard once you get started.

You need to create a derived ConfigurationSection class to define the <routes> section (and then add <section> to the configuration to associate the <routes> element with your type).

Then you need a type to define each item in the collection and, by default, the default property for your second type for the collection.

After all this is configured, at runtime you will get access to the configuration section:

 var myRoutes = ConfigurationManager.GetSection("routes") as RoutesConfigSection; 

There are several articles on my blog against this backdrop: http://blog.rjcox.co.uk/category/dev/net-core/

As noted in another answer, MSDN also has coverage (much better than before).

+2
source

If you do not want to create a class to represent your configuration section, you can do this:

 var configSection = ConfigurationManager.GetSection("sectionGroup/sectionName"); var aValue = (configSection as dynamic)["ValueKey"]; 

Converting to dynamic allows you to access key values ​​in configSection. You may need to add a breakpoint and peak in configSection to see what is and what ValueKey to use.

+1
source

Source: https://habr.com/ru/post/899119/


All Articles