2015-02-05 39 views
1

晚上好,我在一個小項目上工作,我寫的ConfigurationSection沒有返回我放入web.config中的數據。C#ConfigurationSection Propeties是空的

在這裏輸入的代碼

我的代碼:

public class AdminSection : ConfigurationSection 
    { 
     private static AdminSection uniqueInstance; 

    public static AdminSection Instance 
    { 
     get { return uniqueInstance ?? (uniqueInstance = new AdminSection()); } 
    } 


    private AdminSection() 
    {   
    } 

    [ConfigurationProperty("Username", IsRequired =true)] 
    public String Username 
    { 
     get { return (String)this["Username"]; } 
    } 

    [ConfigurationProperty("Password", IsRequired = false)] 
    public String Password 
    { 
     get { return (String)this["Password"]; } 
    } 
} 

這裏是我的web.config

<configuration> 
    <configSections> 
    <section name="Admin" type="cms.Configs.AdminSection, cms.cms"/> 
    </configSections> 
    <system.web> 
    <compilation debug="true" targetFramework="4.5" /> 
    <httpRuntime targetFramework="4.5" /> 
    </system.web> 

    <appSettings> 
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> 
    </appSettings> 
    <Admin> 
    <Username>test</Username> 
    <Password>test2</Password> 
    </Admin> 
</configuration> 

當我TRIE調用下面

Username.Value == Configs.AdminSection.Instance.Username 

我不是獲得任何價值在AdminSection中。

你們有沒有對我可能做錯什麼的一個線索?

+0

有你提到的如何做到這一點[MSDN的ConfigurationSection類](HTTPS MSDN文檔:// MSDN。 microsoft.com/en-us/library/system.configuration.configurationsection%28v=vs.110%29.aspx) – MethodMan 2015-02-05 22:13:28

+0

也許配置管理器無法實例化類? 你嘗試將構造函數從Private改爲Public? – Marty 2015-02-05 22:17:15

+0

是的,我試圖讓它公開,我也試過不使用實例,但以下內容:AdminSection test = new AdminSection(); if(Username.Value == test.Username && UserPass.Value == test.Password), – Mickboe1 2015-02-05 22:21:25

回答

0

發現awnser我忘了執行以下操作:

公共AdminSection聯繫

{ 
    get 
    { 
     try 
     { 
      if (_instance == null) 
      { 
       _instance = ConfigurationManager.GetSection("Admin") as AdminSection; 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 
     return _instance; 
    } 
} 
相關問題