Web.config appSettings: complex values

天涯浪子 提交于 2019-12-04 07:28:11
Alex Aza

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; }
}

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!