Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom section/collection in Web.Config [duplicate]

I've got a bunch of routes that I want to be able to throw in my Web.Config file. I need one key and two value fields for each section/item in the collection. Something along the lines of this...

<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 this possible?

like image 673
cllpse Avatar asked Oct 12 '11 09:10

cllpse


2 Answers

Yes. And not too hard once you have a start.

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

You'll then need a type to define each element of the collection and, flagged as default, a property on your second type for the collection.

After all this is set up, at runtime you access your configuration section as:

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

My blog has a few articles on the background to this: http://blog.rjcox.co.uk/category/dev/net-core/

As noted in another answer there is also coverage (a lot better than it used to be) on MSDN.

like image 144
Richard Avatar answered Oct 26 '22 14:10

Richard


If you don't want to create a class to represent your config section you can do this:

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

Converting to dynamic lets you access the key values in configSection. You may have to add a break point and peak in configSection to see what is there and what ValueKey to use.

like image 37
Richard Garside Avatar answered Oct 26 '22 14:10

Richard Garside