10

我有一些奇怪的事情,我希望 .Net 专家可以帮助我。

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

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

我在我的开发机器上运行它(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");

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

所以,我很高兴(尽管我的应用程序正在运行)但我脑海中的那个小 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());
                }
            }
        }
    }
}

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

<?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>

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

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

进程监视器

我运行Process Monitor并像这样设置过滤器:

过程监控过滤器

剩下的 508 个事件都是以下事件之一:

  • 未找到姓名
  • 没有更多的条目
  • 未找到路径
  • 只有读者锁定的文件
  • 没有这样的文件(对于C:\Windows\assembly\NativeImages_v4.0.30319_32\mscorlib\93e7df09dacd5fef442cc22d28efec83\mscorlib.ni.dllC:\Users\Public\configtest\AppConfigTestConsoleApplication.exe.config只有一次)
  • 缓冲区溢出(对于HKCU\Control Panel\Desktop\MuiCached\MachinePreferredUILanguagesHKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cache

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

4

3 回答 3

10

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

于 2013-01-16T14:30:14.010 回答
6

ConfigurationManager.GetSection(String)

检索应用配置文件、本地用户配置文件和漫游配置文件合并得到的配置文件。


ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel)

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

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

于 2012-11-23T12:24:26.453 回答
0

我知道这是一个旧线程,但我最近在与客户合作时遇到了这个问题,并认为我会发布另一个建议。在我的情况下,问题是使用非静态 ConfigurationManager 方法,这可能会在某些特定条件下导致 SecurityException(应用程序面向 .NET Framework 4 并安装在网络驱动器上,在这种情况下,Windows 更新也被禁用)。以下是有关此问题的更多信息以及 Microsoft 的修补程序:

https://support.microsoft.com/en-us/help/2580188/fix-system.security.securityexception-occurs-when-a-.net-framework-4-based-application-that-c​​alls-a-static -method-in-the-system.configuration.configurationmanager-class-runs-on-a-network-share

于 2017-03-10T17:00:38.937 回答