C # WebApp partial log4net trust (high or medium) not working

I created a simple .NET 4 web application in VS2010 and added a link to log4net 1.2.11.0 (latest version).

In this project, I created the Logger class (see the end of this post). When I call this class Logger ( Logger.Fatal("Test"); ) in a full trust environment, everything works correctly. However, when I change the trust level to high (or medium), it fails with the following exception:

 System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeLoadException: Inheritance security rules violated while overriding member: 'log4net.Util.ReadOnlyPropertiesDictionary.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden. at log4net.Repository.Hierarchy.Hierarchy..ctor(ILoggerFactory loggerFactory) at log4net.Repository.Hierarchy.Hierarchy..ctor() --- End of inner exception stack trace --- at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at log4net.Core.DefaultRepositorySelector.CreateRepository(String repositoryName, Type repositoryType) at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType, String repositoryName, Boolean readAssemblyAttributes) at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType) at log4net.Core.DefaultRepositorySelector.GetRepository(Assembly repositoryAssembly) at log4net.Core.LoggerManager.GetRepository(Assembly repositoryAssembly) at log4net.Config.XmlConfigurator.Configure() at UtilClasses.Logger..cctor() in c:\users\***\documents\visual studio 2010\Projects\TestLogging\TestLogging\Default.aspx.cs:line 35 

This exception is thrown in log4net.Config.XmlConfigurator.Configure(); . So it looks like my application cannot even read my web.config

I found that adding requestPermissions="false" in the <section> should help, however, now I can not start the application at all.

Do you have any tips on how to fix this?

Registrar Class :

 public static class Logger { private static readonly log4net.ILog log; static Logger() { try { log4net.Config.XmlConfigurator.Configure(); log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); } catch (Exception e) { System.Diagnostics.Debug.Write(e.ToString()); } } public static void LogInfo(string information) { log.Info(information); } public static void LogError(string erroMessage, Exception ex) { log.Error(erroMessage, ex); } public static void LogWarnings(string warningText) { log.Warn(warningText); } public static void Fatal(string fatalText) { log.Fatal(fatalText); } } 

Configuration File (web.config):

 <?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <system.web> <compilation debug="true" targetFramework="4.0" /> <trust level="High" /> </system.web> <log4net debug="true"> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="log\logfile.txt" /> <appendToFile value="true" /> <rollingStyle value="Date" /> <datePattern value="yyyy-MM-dd" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date{dd-MM-yyyy HH:mm:ss,fff} [%-2p] - %C.%M - %m%n" /> </layout> </appender> <root> <level value="ALL" /> <appender-ref ref="RollingFileAppender" /> </root> </log4net> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration> 

Full debugger output (without w3wp info):

 'w3wp.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll' log4net: log4net assembly [log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. Loaded from [C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\testlogging\57d742cb\fe23fd98\assembly\dl3\5a80c88f\005a56f5_5784cc01\log4net.DLL]. (.NET Runtime [4.0.30319.261] on Microsoft Windows NT 6.1.7601 Service Pack 1) log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy] log4net: Creating repository for assembly [TestLogging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] log4net: Assembly [TestLogging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\testlogging\57d742cb\fe23fd98\assembly\dl3\a4f1c9bb\cc1c77d4_ce01cd01\TestLogging.DLL] log4net: Assembly [TestLogging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified. log4net: Assembly [TestLogging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy] log4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy] A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeLoadException: Inheritance security rules violated while overriding member: 'log4net.Util.ReadOnlyPropertiesDictionary.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden. at log4net.Repository.Hierarchy.Hierarchy..ctor(ILoggerFactory loggerFactory) at log4net.Repository.Hierarchy.Hierarchy..ctor() --- End of inner exception stack trace --- at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at log4net.Core.DefaultRepositorySelector.CreateRepository(String repositoryName, Type repositoryType) at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType, String repositoryName, Boolean readAssemblyAttributes) at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType) at log4net.Core.DefaultRepositorySelector.GetRepository(Assembly repositoryAssembly) at log4net.Core.LoggerManager.GetRepository(Assembly repositoryAssembly) at log4net.Config.XmlConfigurator.Configure() at UtilClasses.Logger..cctor() in c:\users\***\documents\visual studio 2010\Projects\TestLogging\TestLogging\Default.aspx.cs:line 35 

[edit] I turned on the log4net source, not the DLL, and found out that the exception occurs when log4net creates a new instance of the repository. This is in DefaultRepositorySelector.cs , (line 424-426):

  // Call the no arg constructor for the repositoryType var x = Activator.CreateInstance(repositoryType); rep = (ILoggerRepository)x; 
+4
source share
3 answers

It turned out that I had to change the source for log4net myself.

First of all, the log4net build profile was incorrect in the original version. We had to add the NET4 qualifier to it. Also in Assemblyinfo.cs, the following attribute [assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)] was to be added to rule 40.

Old code:

 #if (!NETCF) // // If log4net is strongly named it still allows partially trusted callers // [assembly: System.Security.AllowPartiallyTrustedCallers] #endif 

New code:

 #if (!NETCF) // // If log4net is strongly named it still allows partially trusted callers // [assembly: System.Security.AllowPartiallyTrustedCallers] [assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)] #endif 

After compiling now in release mode, I have no problems.

+9
source

I found this blog post that describes how to solve your problem.

These are the changes necessary to make Log4Net work in a trust environment.

  • Added the declaration of the log4Net section in the configSections section of web.config and verify that the requirePermission attribute is set to false.
  • Moved log4Net settings to web.config file.
  • Removed XmlConfigurator assembly attribute from AssemblyInfo.cs
  • Added call XmlConfigurator.Configure () to the Application_Start Method in Global.asax.cs.
+2
source

After applying the above, you got another error:

Security exception Description: The application attempted to perform an operation not permitted by the security policy. To grant this application the required permissions, contact your system administrator or change the application trust level in the configuration file.

Exception Details: System.Security.SecurityException: A permission request of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089' failed.

Above was resolved by adding

 <system.web> <trust level="Full" /> </system.web> 
+2
source

Source: https://habr.com/ru/post/1401347/


All Articles