2015-11-17 32 views
1

我的web配置如下:我可以创建自定义方法ConfigurationManager中类

<appSettings> 
    <add key="One" value="1" xdt:Transform="Insert"/> 
    </appSettings> 

如果我需要访问的值为1,我可以写下面的代码:

ConfigurationManager.AppSettings("One"); 

但如果web配置是一样,

<countryAppSettings> 
    <add key="Two" value="2" xdt:Transform="Insert"/> 
    </countryAppSettings> 

我可以访问在以下形式的值,使用一个辅助类为ConfigurationManagerç lass

ConfigurationManager.CountryAppSettings("Two"); 

这是可能的C#?

+1

http://softwarebydefault.com/code-samples/extends-configurationmanager-get-values-by-type /你可能不想看这篇文章 – MajkeloDev

+0

@MajkeloDev它没有回答我的问题。 –

+0

@wudzik我不认为这是一个重复的问题,即尝试访问配置文件中的自定义部分。我相信这是关于创建自定义部分以及他们如何具有更类似于https://msdn.microsoft.com/en-us/library/2tw134k3.aspx – Ian

回答

0

是的,您可以这样做,但您也需要在配置文件中包含自定义配置部分。有一个MSDN文章here描述如何做到这一点。

因此,您需要在您的自定义配置部分添加第一:

<configuration> 
    <configSections> 
    <sectionGroup name="countrySettings"> 
     <section name="countrySetting" type="Custom.CountrySettingSection" allowLocation="true" allowDefinition="Everywhere" /> 
    </sectionGroup> 
    </configSections> 
</configuration> 

你会那么通常定义设置更多像这样的,这是伟大的,如果你有一个非常丰富的对象:

<countrySetting customKey="2"> 
    <richerObject>2</richerObject> 
</countrySetting> 

你会再需要像这样构成的支持对象:

namespace Custom 
{ 
public class CountrySettingSection : ConfigurationSection 
    { 
     // Create a "customKey" attribute. 
     [ConfigurationProperty("customKey", DefaultValue = "0", IsRequired = false)] 
     public int CustomKey 
     { 
      get 
      { 
       return (int)this["customKey"]; 
      } 
      set 
      { 
       this["customKey"] = value; 
      } 
     } 
} 
0
  1. 你不能这样创建。也许应该访问此链接 https://msdn.microsoft.com/en-us/library/bb383977.aspx
  2. ConfigurationManager.AppSetting属性,没有方法。这 属性类型是NameValueCollection中,你可以使用这样

    ConfigurationManager.AppSettings["One"]ConfigurationManager.AppSettings.GetValues("One")

  3. 您可以自定义你的web.config https://msdn.microsoft.com/en-us/library/2tw134k3.aspx

+0

大多数情况下,这种仅依赖链接的答案(特别是土耳其语中的答案)是不鼓励的。SO上的答案应该是解决方案寻求者的一个停止点,并且链接有一个突破的趋势。如果有关于链接的相关信息,请围绕此建立一个答案,并且只包含引用您的解决方案的链接。 – Tgsmith61591

相关问题