共用方式為


CA2142: Transparent code should not be protected with LinkDemands

Item Value
RuleId CA2142
Category Microsoft.Security
Breaking change Breaking

Cause

A transparent method requires a SecurityAction or other security demand.

Note

This rule has been deprecated. For more information, see Deprecated rules.

Rule description

This rule fires on transparent methods that require LinkDemands to access them. Security transparent code should not be responsible for verifying the security of an operation, and therefore should not demand permissions. Because transparent methods are supposed to be security neutral, they should not be making any security decisions. Additionally, safe critical code, which does make security decisions, should not be relying on transparent code to have previously made such a decision.

How to fix violations

To fix a violation of this rule, remove the link demand on the transparent method or mark the method with SecuritySafeCriticalAttribute attribute if it is performing security checks, such as security demands.

When to suppress warnings

Do not suppress a warning from this rule.

Example

In the following example, the rule fires on the method because the method is transparent and is marked with a LinkDemand PermissionSet that contains an SecurityAction.

using System;
using System.Security.Permissions;

namespace TransparencyWarningsDemo
{

    public class TransparentMethodsProtectedWithLinkDemandsClass
    {
        // CA2142 violation - transparent code using a LinkDemand.  This can be fixed by removing the LinkDemand
        // from the method.
        [PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
        public void TransparentMethod()
        {
        }
    }
}

Do not suppress a warning from this rule.