Web.config appSettings: complex values

2020-06-21 05:20发布

问题:

Is Web.config's appSettings section only capable of storing simple strings like this?

   <appSettings>
     <add key="OKPage" value="http://mysite.com/okpage.html" />
   </appSettings>

or I can have more complex values like CDATA or nested values? If not, is this the only place in Web.config where to store custom settings? Thanks

回答1:

You can make any XmlSerializable class as a setting.

I answered to the similar question here: Custom type application settings in ASP.NET
Also there is a sample project attached.

Here is an example of the settings from my config file:

<setting name="MyEndPoints"
          serializeAs="Xml">
  <value>
    <ArrayOfEndPoint xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <EndPoint>
        <HostName>10.40.10.9</HostName>
        <Port>22634</Port>
      </EndPoint>
      <EndPoint>
        <HostName>10.40.10.9</HostName>
        <Port>22635</Port>
      </EndPoint>
    </ArrayOfEndPoint>
  </value>
</setting>

Custom class for settings:

public class EndPoint
{
    public string HostName { get; set; }

    public int Port { get; set; }
}


回答2:

Keys inside appSettings are retrieved as NameValueCollection which by definition

Represents a collection of associated String keys and String values that can be accessed either with the key or with the index.

So you can have only the data type string as value for an AppSettings key

And yes, AppSettings is the only place where you can store your settings.
MSDN defines AppSettings like this.

Contains custom application settings, such as file paths, XML Web service URLs, or any information that is stored in the.ini file for an application.



回答3:

The AppSettings section is a NameValueCollection which contain strings. (NameValueCollection has an Add(string, string) method.) If you use CDATA inside the key/value than it will be just entered to the collection as a string. You will have to parse it yourself to for example XML.

The AppSetttings section has as a pre for settings that there is already written a wrapper where you can access the keys typesafe from your code. On the other hand your web.config is just XML, where you can add your own types. You will need to write some code to access these sections.