Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store custom data in web.config?

I have the following method in my apiController:

public IEnumerable<something> GetData(DataProvider dataProvider)
{
    return dataProvider.GetData();
}

What I need is to invoke this method from javascript and pass it a parameter of DataProvider derived type. I can handle this by passing string, e.g. "FirstProvider" and than write N number of if's in GetData() method to create an instance of proper type.

But is there some way that I can write in web.config file something like:

<DataProviders>
  <type = FirstDataProvider, alias = "FirstProvider">
  <type = SecondDataProvider, alias = "SecondProvider">
</DataProviders>

Change getData method to:

public IEnumerable<something> GetData(string dataProviderAlias)
{
                // get provider type by it's alias from web congfig,
                // then instantiated and call: 
    return dataProvider.GetData();
}

And then find and instantiate the type by it's alias?

Note: I accepted the answer below cause it's pointed me in a right direction, but msdn says that IConfigurationSectionHandler is deprecated.
So I used ConfigurationSection, ConfigurationElementCollection, ConfigurationElement classes instead to build custom config section.

like image 311
Aleksei Chepovoi Avatar asked Aug 21 '13 22:08

Aleksei Chepovoi


1 Answers

You can store arbitrary data in web.config in the appSettings element:

<configuration>
   <appSettings>
      <add key="FirstAlias" value="FirstProvider" />
      <add key="SecondAlias" value="SecondProvider" />
   </appSettings>
</configuration>

And you can then read the values using:

String firstAlias = System.Configuration.ConfigurationManager.AppSettings["FirstAlias"];
String secondAlias = System.Configuration.ConfigurationManager.AppSettings["SecondAlias"];

It's built-in. It's supported. It's where you're supposed to store custom data.

like image 148
Ian Boyd Avatar answered Sep 19 '22 12:09

Ian Boyd