asp.net - 在中等信任度下以编程方式修改配置部分

标签 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 文件中的“服务器”属性。

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

最佳答案

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

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

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

关于asp.net - 在中等信任度下以编程方式修改配置部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4841977/

相关文章:

javascript - 在 ASP.Net MVC 5 中将 javascript 数组从 View 传递到 Controller

c# - WPF 的 CefSharp 不显示

.net - 防止许多不同的 MVC URL 填充 ASP.NET 缓存

asp.net - 将字符串数组存储在 appSettings 中?

asp.net-mvc - 在 Asp.net MVC 应用程序中使用 SSL 与验证 key 的区别

c# - 中等信任度的 NHibernate 2.1.2

asp.net - HttpWebRequest.GetResponse() 在 .NET 3.5 上挂起但在 .NET 4 上工作

asp.net - 如何确定哪个父配置文件正在锁定 web.config 设置?

asp.net - 反射会带来什么风险? (中等信任度)

asp.net - .NET 2.0 和 MySql 处于中等信任模式