简体   繁体   中英

How can I access web.config from an ASP.NET Custom Control?

Inside my web.config file I've got code like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    ...
    <section name="UninstallSurveySettings" type="dashboard.UninstallSurveyConfig" />
  </configSections>
  ...
  <UninstallSurveySettings>
    <add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
  </UninstallSurveySettings>
   ...
</configuration>

I need to be able to access this field from my custom control. The control can be dropped into any website and needs to check that site's web.config for the fileLocation value in UninstallSurveySetting.

I've tried a couple different approaches with no luck. Any help on this would be greatly appreciated.

Much easier to use AppSettings .

Web.config:

<configuration>    
    <appSettings>
        <add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
    </appSettings>    
</configuration>

Code:

string location = System.Configuration.ConfigurationManager.AppSettings["fileLocation"];

If your section will become more complex, then:

var section = (NameValueFileSectionHandler)ConfigurationManager.GetSection("UninstallSurveySettings");
if (section != null)
{
    // access section members
}

PS

Maybe you want to use ConfigurationSection class instead of handler.

In ASP.NET MVC 3 the tag cannot be a direct child of (it results in a configuration error).

How about adding your key to the section . Then you can easily access it via the ConfigurationManager.AppSettings collection.

using System.Configuration.ConfigurationManager and you will be able to get what you want from the web.config

I was able to solve this by creating a configuration class for it and placing this code in the web.config:

<section name="UninstallSurveyConfig" type="dashboard.UninstallSurveyConfig" />
..

<UninstallSurveyConfig dirFileLocation="C:\inetpub\wwwroot\build\output" webFileLocation="~/output" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM