为什么使用ConfigurationManager.GetSection会导致"SecurityException:Request failed",但ConfigurationManager.OpenExeConfiguration却没有?

kmp*_*kmp 10 .net c# .net-4.0

我有一些好奇的东西,我希望.Net专家可以帮助我.

我有一个自定义配置部分,为了掌握它,我这样做:

var s = (TestConfigurationSection)ConfigurationManager
    .GetSection("testSection");
Run Code Online (Sandbox Code Playgroud)

我在我的开发机器上运行它(Windows 764位,Windows完全是最新的),它运行正常.

我把那个代码带到了exe中,然后把它c:\users\public放在Windows Server 2008 R2机器上的一个目录里,以管理员的身份打开命令提示符,运行它然后我得到:

System.Configuration.ConfigurationErrorsException:为testSection创建配置节处理程序时发生错误:请求失败.(C:\ Users\Public\configtest\AppConfigTestConsoleApplication.exe.Config第10行)---> System.Security.SecurityException:请求失败.

现在我更改了代码来执行此操作:

var config = ConfigurationManager.OpenExeConfiguration(
    ConfigurationUserLevel.None);
var s = (TestConfigurationSection) config
    .GetSection("testSection");
Run Code Online (Sandbox Code Playgroud)

它在两台机器上都能正常工作.

所以,我感到有点高兴(就像我的申请工作一样)但是我头脑中的那个小Gremlin很困惑所以我在这里问:

为什么会这样?


重现步骤

在visual studio 2010中创建一个名为AppConfigTestConsoleApplication的新的.net 4控制台应用程序项目Program.cs,并将以下内容替换为:

using System;
using System.Configuration;

namespace AppConfigTestConsoleApplication
{
    public class TestConfigurationSection : ConfigurationSection
    {
        [ConfigurationProperty("someSetting")]
        public int SomeSetting
        {
            get { return (int) this["someSetting"]; }
            set { this["someSetting"] = value; }
        }
    }

    internal class Program
    {
        private static void Main()
        {
            try
            {
                var s = (TestConfigurationSection) ConfigurationManager
                    .GetSection("testSection");
                Console.WriteLine("First Method worked: " + s.SomeSetting);
            }
            catch (Exception ex)
            {
                Console.WriteLine("First method failed");
                Console.WriteLine(ex.ToString());

                if (ex.InnerException != null)
                {
                    var eex = ex.InnerException as SecurityException;
                    Console.WriteLine("Action: '{0}'", eex.Action.ToString());
                    Console.WriteLine("Demanded: '{0}'", eex.Demanded.ToString());
                    Console.WriteLine("RefusedSet: '{0}'", eex.RefusedSet);
                    Console.WriteLine("GrantedSet: '{0}'", eex.GrantedSet);
                }

                try
                {
                    var config = ConfigurationManager.OpenExeConfiguration(
                        ConfigurationUserLevel.None);

                    var s = (TestConfigurationSection) config
                        .GetSection("testSection");

                    Console.WriteLine("Second Method worked: " 
                        + s.SomeSetting);
                }
                catch (Exception x)
                {
                    Console.WriteLine("Even the second method failed!");
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后添加应用程序配置文件并使用以下内容替换内容:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>  
    <section
      name="testSection"
      type="AppConfigTestConsoleApplication.TestConfigurationSection, AppConfigTestConsoleApplication"
      requirePermission="false"
      allowDefinition="Everywhere" />  
  </configSections>
  <testSection someSetting="10"></testSection>
</configuration>
Run Code Online (Sandbox Code Playgroud)

编译并运行,这是我得到的输出:

C:\Users\Public\configtest>AppConfigTestConsoleApplication.exe
First method failed
System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for testSection: Request failed. (C:\Users\Public\configtest\AppConfigTestConsoleApplication.exe.Config line 10) ---> System.Security.SecurityException: Request failed.
   at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags)
   at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, UInt32 invocationFlags)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
   at System.Configuration.TypeUtil.InvokeCtorWithReflectionPermission(ConstructorInfo ctor)
   at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
   at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
   at System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
   at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
   --- End of inner exception stack trace ---
   at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecordsectionRecord, Object parentResult)
   at System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject)
   at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
   at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
   at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
   at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
   at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
   at System.Configuration.ConfigurationManager.GetSection(String sectionName)
   at AppConfigTestConsoleApplication.Program.Main()
Action: 'Demand'
Demanded: '<PermissionSet class="System.Security.PermissionSet"
version="1"
Unrestricted="true"/>
'
RefusedSet: ''
GrantedSet: ''
Second Method worked: 10
Run Code Online (Sandbox Code Playgroud)

进程监视器

我运行Process Monitor并设置过滤器,如下所示:

进程监视器筛选器

这留下了508个事件,它们都是:

  • 名字没找到
  • 没有更多的条目
  • 路径没找到
  • 仅与读者锁定的文件
  • 没有这样的文件(仅适用于C:\ Windows\assembly\NativeImages_v4.0.30319_32\mscorlib\93e7df09dacd5fef442cc22d28efec83\mscorlib.ni.dllC:\ Users\Public\configtest\AppConfigTestConsoleApplication.exe.config)
  • BUFFER OVERFLOW(适用于HKCU\Control Panel\Desktop\MuiCached\MachinePreferredUILanguages,HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cache,

有没有人有任何建议可能会设置什么过滤器来找到根本原因?

its*_*urs 10

当程序集被"阻止"时(在文件属性选项卡下),我有同样的行为.这些文件通过zip通过电子邮件发送给管理员.当他保存了附件时,块位被添加......就像从互联网上下载文件一样.清除块后,它工作正常.


Cod*_*ter 6

ConfigurationManager.GetSection(String):

检索通过合并应用程序配置文件,本地用户配置文件和漫游配置文件获得的配置文件.


ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel):

userLevel参数通过指示是否没有用户级别(配置文件与应用程序位于同一目录中)来确定要打开的配置文件的位置

所以,他们正在打开不同的文件.使用ProcessMonitor查看正在访问的文件以及发生异常的原因以及在哪个文件上查找.