【问题标题】:Modify configuration section programmatically in medium trust在中等信任下以编程方式修改配置部分
【发布时间】:2011-06-18 00:54:51
【问题描述】:

我的应用程序中有一个自定义的 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 文件中的“服务器”属性。

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

【问题讨论】:

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


    【解决方案1】:

    简短的回答 - 不。 .NET 团队(据称)打算在 v4 中解决这个问题,但它没有发生。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      • 2012-12-02
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多