We recommend using Visual Studio 2017

CA2141:Transparent methods must not satisfy LinkDemands


The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at CA2141:Transparent methods must not satisfy LinkDemands.

|Breaking Change|Breaking|

A security transparent method calls a method in an assembly that is not marked with the AllowPartiallyTrustedCallersAttribute (APTCA) attribute, or a security transparent method satisfies a F:System.Security.Permissions.SecurityAction.LinkDemand for a type or a method.

Satisfying a LinkDemand is a security sensitive operation which can cause unintentional elevation of privilege. Security transparent code must not satisfy LinkDemands, because it is not subject to the same security audit requirements as security critical code. Transparent methods in security rule set level 1 assemblies will cause all LinkDemands they satisfy to be converted to full demands at run time, which can cause performance problems. In security rule set level 2 assemblies, transparent methods will fail to compile in the just-in-time (JIT) compiler if they attempt to satisfy a LinkDemand.

In assemblies that usee Level 2 security, attempts by a security transparent method to satisfy a LinkDemand or call a method in a non-APTCA assembly raises a MethodAccessException; in Level 1 assemblies the LinkDemand becomes a full Demand.

To fix a violation of this rule, mark the accessing method with the SecurityCriticalAttribute or SecuritySafeCriticalAttribute attribute, or remove the LinkDemand from the accessed method.

Do not suppress a warning from this rule.

In this example, a transparent method attempts to call a method that has a LinkDemand. This rule will fire on this code.

using System;
using System.Security.Permissions;

namespace TransparencyWarningsDemo

    public class TransparentMethodSatisfiesLinkDemandsClass
        [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
        public void LinkDemandMethod() { }

        public void TransparentMethod()
            // CA2141 violation - transparent method calling a method protected with a link demand.  Any of the
            // following fixes will work here:
            //  1. Make TransparentMethod critical
            //  2. Make TransparentMethod safe critical
            //  3. Remove the LinkDemand from LinkDemandMethod  (In this case, that would be recommended anyway
            //     since it's level 2 -- however you could imagine it in a level 1 assembly)