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);
    }
}