How to fix 'Reference does not allow partially trusted callers' warnings in Visual Studio

By FoxLearn 11/11/2024 4:35:53 AM   110
This warning typically arises in situations where your project is running in a partial trust environment and the referenced assembly does not explicitly support being called in partial trust.

For example:

Warning 1   Reference 'Common.Logging.NLog' does not allow partially trusted callers.
Warning 2   Reference 'Common.Logging' does not allow partially trusted callers.
Warning 3   Reference 'NLog' does not allow partially trusted callers.
Warning 4   Use of app.config binding redirects requires full trust.

The Visual Studio Error List shows many warnings of the pattern "Reference '<nuget package>' does not allow partially trusted callers" when your project references assemblies that are not marked to support partial trust, potentially due to restrictions in your project's environment.

You can fix by adding to App.config like this:

<runtime>             
     <NetFx40_LegacySecurityPolicy enabled="true" />
</runtime> 

If your application runs in partial trust (e.g., ClickOnce or sandboxed environments), you may need to change the trust level to Full Trust.

Go to Project Properties > Security tab.

security

Ensure Full Trust is selected (uncheck Enable ClickOnce Security Settings if it's checked).

This will ensure that the code can access the referenced assemblies without encountering partial trust restrictions.

If your assembly is a third-party library that doesn't support partial trust and you cannot modify it, look for an alternative library that either doesn't require full trust or has been marked with [AllowPartiallyTrustedCallers].

using System.Security;

[assembly: AllowPartiallyTrustedCallers]

namespace MyNamespace
{
    public class MyClass
    {
        // Your class code here
    }
}