以中等信任度以编程方式修改配置部分

时间:2011-01-30 08:39:24

标签: asp.net web-config medium-trust

我的应用程序中有一个自定义ConfigurationSection:

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

在我的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>

阅读该部分工作正常。我遇到的问题是,当我通过

阅读该部分时
var settings = (SettingsSection)WebConfigurationManager.GetSection("mySettingsGroup/Setting");

然后我继续修改Server属性:

   settings.Server = "something";

这不会修改web.config文件中的“Server”属性。

注意:这需要在中等信任下工作,所以我不能使用工作正常的WebConfigurationManager.OpenWebConfiguration。是否有明确的方法告诉ConfigSection保存自己?

1 个答案:

答案 0 :(得分:3)

简短回答 - 不。 .NET团队(据称)意图在v4中解决这个问题,但事情并没有发生。

原因是因为使用WebConfigurationManager.GetSection会返回嵌套的只读NameValueCollection,当您更改其值时,它们不会保留。正如您已正确确定的那样,使用WebConfigurationManager.OpenWebConfiguration是获取配置的读写访问权限的唯一方法 - 但随后您将获得FileIOPermission异常,因为OpenWebConfiguration尝试将所有继承的配置加载到web.config - 其中包括C:\WINDOWS\Microsoft.NET\Framework中的机器级web.config和machine.config文件,这些文件明显超出中等信任范围。

长答案 - 使用XDocument / XmlDocument和XPath来获取/设置配置值。

相关问题