How to open a SectionGroup in an ASP.NET web application?

强颜欢笑 提交于 2019-12-05 02:06:48
System.Configuration.Configuration config =
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
return config.GetSectionGroup(SectionGroupName);

should work in asp.net.

Kiran

Inside the web application, try using WebConfigurationManager. You will need a mechanism to detect if you are in a web context or exe context and use some design pattern to switch between contexts. A simple way to do this is check if HttpContext.Current is null (not null indicates web context and a null value indicates a exe context).

IMO, something like this should work,

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

It will be more complex if you don't want the dependency on the System.web dll

I haven't tested it.

ConfigurationManager.GetSection("SectionGroupName/GroupName")

i.e. e.g.

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

&

var config = ConfigurationManager.GetSection("RFERL.Mvc/routes") as RoutesConfigurationSection;

Posting in case this helps anyone. I used this answer to be able to read an Umbraco configuration.

    private static string CdnUrl()
    {
        // Unit test vs web environment
        Configuration configuration;
        if (HttpContext.Current == null)
        {
            configuration = ConfigurationManager.OpenExeConfiguration(null);
        }
        else
        {
            configuration = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
        }

        // Grab Umbraco config
        ConfigurationSectionGroup umbracoConfiguration = configuration.GetSectionGroup("umbracoConfiguration");
        FileSystemProvidersSection fileSystemProviders = (FileSystemProvidersSection)umbracoConfiguration.Sections.Get("FileSystemProviders");

        // Return the information needed
        var cdnUrl = fileSystemProviders.Providers["media"].Parameters["rootUrl"].Value;
        return cdnUrl;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!