如何在ASP.NET Web应用程序中打开SectionGroup?

And*_*ott 11 asp.net configurationmanager

我有一个小的ASP.NET Web应用程序托管在集成测试中(在NUnit中执行).我的产品代码通常可以从web.config或app.config文件中找到配置数据,但出于某种原因,在托管ASP.NET时,我似乎ArgumentException在执行第一个命令时得到了:

var configuration = ConfigurationManager.OpenExeConfiguration(null);
return configuration.GetSectionGroup(SectionGroupName);
Run Code Online (Sandbox Code Playgroud)

不在独立的exe内部运行时必须指定exePath.

我不知道该把什么放在这里.我的产品没有一个合理的exePath作为参数传递给这个方法,因为它通常在Web服务器中运行.此外,通常可以使用以下方式打开普通Sections(而不是SectionGroups):

ConfigurationManager.GetSection(SectionName)
Run Code Online (Sandbox Code Playgroud)

即使在单元测试中,这也适用于App.config文件以某种方式神奇地被读取.这是我在阅读SectionGroups时想要的.

有任何想法吗?

小智 13

在Web应用程序内部,尝试使用WebConfigurationManager.您将需要一种机制来检测您是在Web上下文还是exe上下文中,并使用一些设计模式在上下文之间切换.一个简单的方法是检查HttpContext.Current是否为null(非null表示Web上下文,null值表示exe上下文).

国际海事组织,这样的事情应该有效,

        Configuration configuration;
        if (HttpContext.Current == null)
            configuration = ConfigurationManager.OpenExeConfiguration(null); // whatever you are doing currently
        else
            configuration = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); //this should do the trick

        configuration.GetSectionGroup(sectionGroupName);
Run Code Online (Sandbox Code Playgroud)

如果您不希望依赖于System.web dll,那将会更复杂

我没有测试过.


Đon*_*nny 5

ConfigurationManager.GetSection("SectionGroupName/GroupName")
Run Code Online (Sandbox Code Playgroud)

即,例如

<configSections>
    <sectionGroup name="RFERL.Mvc" type="System.Configuration.ConfigurationSectionGroup, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
        <section name="routes" type="RFERL.Mvc.Configuration.RoutesConfigurationSection, RFERL.Mvc"/>
    </sectionGroup> 
</configSections>
Run Code Online (Sandbox Code Playgroud)

&

var config = ConfigurationManager.GetSection("RFERL.Mvc/routes") as RoutesConfigurationSection;
Run Code Online (Sandbox Code Playgroud)


ono*_*nof 2

System.Configuration.Configuration config =
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
return config.GetSectionGroup(SectionGroupName);
Run Code Online (Sandbox Code Playgroud)

应该在 asp.net 中工作。