Modify configuration section programmatically in medium trust

江枫思渺然 提交于 2019-12-10 18:52:17

问题


I have a custom ConfigurationSection in my application:

public class SettingsSection : ConfigurationSection
{
    [ConfigurationProperty("Setting")]
    public MyElement Setting
    {
        get
        {
            return (MyElement)this["Setting"];
        }
        set { this["Setting"] = value; }
    }
}

public class MyElement : ConfigurationElement
{
    public override bool IsReadOnly()
    {
        return false;
    }

    [ConfigurationProperty("Server")]
    public string Server
    {
        get { return (string)this["Server"]; }
        set { this["Server"] = value; }
    }
}

In my web.config

  <configSections>
    <sectionGroup name="mySettingsGroup">
      <section name="Setting" 
               type="MyWebApp.SettingsSection"  
               requirePermission="false" 
               restartOnExternalChanges="true"
               allowDefinition="Everywhere"  />
    </sectionGroup>
  </configSections>

  <mySettingsGroup>
    <Setting>
      <MyElement Server="serverName" />
    </Setting>
  </mySettingsGroup>

Reading the section works fine. The issue I'm having is that when I read the section via

var settings = (SettingsSection)WebConfigurationManager.GetSection("mySettingsGroup/Setting");

And then I proceed to modify the Server property:

   settings.Server = "something";

This doesn't modify the "Server" property in the web.config file.

Note: This needs to work under medium-trust, so I can't use WebConfigurationManager.OpenWebConfiguration which works fine. Is there an explicit way to tell the ConfigSection to save itself?


回答1:


Short answer - no. .NET team were (allegedly) meant to fix this in v4, but it didn't happen.

The reason is because using WebConfigurationManager.GetSection returns nested read-only NameValueCollections, which do not persist when you change their values. Using WebConfigurationManager.OpenWebConfiguration, as you've quite rightly ascertained, is the only way to obtain read-write access to the config - but then you'll get a FileIOPermission exception thrown, as OpenWebConfiguration attempts to load all inherited configs down to your web.config - which include the machine-level web.config and machine.config files in C:\WINDOWS\Microsoft.NET\Framework, which are explicitly out-of-scope of Medium Trust.

Long answer - use XDocument / XmlDocument and XPath to get/set config values.



来源:https://stackoverflow.com/questions/4841977/modify-configuration-section-programmatically-in-medium-trust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!