简体   繁体   中英

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, eg "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.

First of all, you can only store valid xml in web.config. <type = FirstDataProvider, alias = "FirstProvider"> is not valid xml.

Second, there are a lot of moving pieces. Please follow the steps carefully -

web.config

Make sure you enter the proper namespace for DataProviders. type="YOUR_APPLICATION.DataProviders" .

<configuration>
  <configSections>
    <section name="DataProviders" type="WebApplication2010.DataProviders" 
        requirePermission="false"/>
  </configSections>
  <DataProviders>
    <Provider type="FirstDataProvider" alias="FirstProvider"/>
    <Provider type="SecondDataProvider" alias="SecondProvider"/>
  </DataProviders>
  ....
</configuration>

Code

public class DataProviders : IConfigurationSectionHandler
{
    private static bool _initialized;
    public static List<Provider> _providers;

    public object Create(object parent, object configContext, XmlNode section)
    {
        XmlNodeList providers = section.SelectNodes("Provider");

        _providers = new List<Provider>();

        foreach (XmlNode provider in providers)
        {
            _providers.Add(new Provider
            {
                Type = provider.Attributes["type"].Value,
                Alias = provider.Attributes["alias"].Value,
            });
        }

        return null;
    }

    public static void Init()
    {
        if (!_initialized)
        {
            ConfigurationManager.GetSection("DataProviders");
            _initialized = true;
        }
    }

    public static IEnumerable<Provider> GetData(string dataProviderAlias)
    {
        return _providers.Where(p => p.Alias == dataProviderAlias);
    }
}

public class Provider
{
    public string Type { get; set; }
    public string Alias { get; set; }
}

Global.asax

For good design practice, you want to read data from web.config only once, and store them in static variables. Therefore, you want to initialize inside Application_BeginRequest of Global.asax.

public class Global : System.Web.HttpApplication
{
    void Application_BeginRequest(object sender, EventArgs e)
    {
        DataProviders.Init();
    }
}

Usage

var providers = DataProviders.GetData("FirstProvider").ToList();

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.

Well, I'm not sure if I understand what you want to achieve, but to implement your idea you need a custom section handler.

http://msdn.microsoft.com/en-us/library/2tw134k3(v=vs.100).aspx

In case that you want to create a database connection for specific dataprovider, see this similar question:

ASP.NET: How to create a connection from a web.config ConnectionString?

In my case, I needed to store two byte[] variables in my Web.Config file. Since it must be valid XML data, I simply stored the contents of the arrays like so:

<appSettings>
    <add key="Array1" value="0,1,2,3,4,5,6,7,8,9" />
    <add key="Array2" value="0,1,2,3,4,5,6,7,8,9" />
</appSettings>

I then call a function that reads this into a C# string, split it into a string[], and parse each string element as a byte into a resulting byte[] and return it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM