CA2145:不应使用 SuppressUnmanagedCodeSecurityAttribute 修饰透明方法

类型名

TransparentMethodsShouldNotUseSuppressUnmanagedCodeSecurity

CheckId

CA2145

类别

Microsoft.Security

是否重大更改

原因

安全透明方法就是用 SecuritySafeCriticalAttribute 方法标记的方法,或者说包含用 SuppressUnmanagedCodeSecurityAttribute 特性标记的方法的类型。

规则说明

SuppressUnmanagedCodeSecurityAttribute 特性修饰的方法有一个隐式的 LinkDemand 作用于调用它的任何方法。 此 LinkDemand 要求调用代码是关键安全的。 将标记对 SuppressUnmanagedCodeSecurity 使用 SecurityCriticalAttribute 特性的方法使此要求对方法的调用方更加明显。

如何解决冲突

要修复该规则的冲突,用 SecurityCriticalAttribute 特性标记该方法或类型。

何时禁止显示警告

不要禁止显示此规则发出的警告。

代码

using System;
using System.Runtime.InteropServices;
using System.Security;

namespace TransparencyWarningsDemo
{

    public class SafeNativeMethods
    {
        // CA2145 violation - transparent method marked SuppressUnmanagedCodeSecurity.  This should be fixed by
        // marking this method SecurityCritical.
        [DllImport("kernel32.dll", SetLastError = true)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool Beep(uint dwFreq, uint dwDuration);
    }
}