为什么具有拒绝安全操作的 PrincipalPermission 仍然允许访问?

Why does PrincipalPermission with a deny securityaction still allow access?

当我注意到我添加的方法

时,我一直在玩弄身份和委托人
[PrincipalPermission(SecurityAction.Deny, Role = "Admin")] 

身份为

GenericIdentity identity = new GenericIdentity("JC", "Type1");
GenericPrincipal principal = new GenericPrincipal(identity, new string[] { "Admin", "User" });
Thread.CurrentPrincipal = principal;

仍然会在不抛出 SecurityException 的情况下被调用,就像它具有 Demand 安全操作时那样。

事实上,即使我像这样拼错了 Role

[PrincipalPermission(SecurityAction.Deny, Role = "asad")] 

它仍然允许我调用该方法而不会引发太多不适

问题是,为什么?

我的全部代码:

static void Main(string[] args)
        {
            GenericIdentity identity = new GenericIdentity("JC", "Type1");
            GenericPrincipal principal = new GenericPrincipal(identity, new string[] { "Admin", "User" });
            Thread.CurrentPrincipal = principal;
            UsePrincipal();
        }

        static void UsePrincipal()
        {
            Console.WriteLine(Thread.CurrentPrincipal.Identity);
            try
            {
                DevWork();
            }
            catch
            {
                Console.WriteLine("You Bad!");
            }
            Console.ReadKey();
        }

        [PrincipalPermission(SecurityAction.Deny, Role = "Admin")]
        static void DevWork() // Will be executed no matter what the role is
        {
            Console.WriteLine("You Good!");
            Console.ReadKey();
        }

您可以在 SecurityAction 的文档中读到 Deny 已过时并且:

In the .NET Framework 4, runtime support has been removed for enforcing the Deny, RequestMinimum, RequestOptional, and RequestRefuse permission requests. These requests should not be used in code that is based on .NET Framework 4 or later.

由于您使用的是 .NET 4.5.2 - 您的 Deny 请求只是被忽略了。