PrincipalPermissionAttribute(SecurityAction) Constructor

Definition

Caution

PrincipalPermissionAttribute is not honored by the runtime and must not be used.

Initializes a new instance of the PrincipalPermissionAttribute class with the specified SecurityAction.

C#
[System.Obsolete("PrincipalPermissionAttribute is not honored by the runtime and must not be used.", true, DiagnosticId="SYSLIB0002", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public PrincipalPermissionAttribute(System.Security.Permissions.SecurityAction action);
C#
public PrincipalPermissionAttribute(System.Security.Permissions.SecurityAction action);

Parameters

action
SecurityAction

One of the SecurityAction values.

Attributes

Examples

The following example demonstrates how to use the PrincipalPermissionAttribute constructor to demand that the current user be an administrator.

Напомена

In Windows Vista, User Account Control (UAC) determines the privileges of a user. If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. By default, you are in the standard user role. To execute the code that requires you to be an administrator, you must first elevate your privileges from standard user to administrator. You can do this when you start an application by right-clicking the application icon and indicating that you want to run as an administrator.

C#
using System;
using System.Threading;
using System.Security.Permissions;
using System.Security.Principal;

class SecurityPrincipalDemo
{
    public static void Main()
    {
        try
        {
            // PrincipalPolicy must be set to WindowsPrincipal to check roles.
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            // Check using the PrincipalPermissionAttribute
            CheckAdministrator();
            // Check using PrincipalPermission class.
            PrincipalPermission principalPerm = new PrincipalPermission(null, "Administrators");
            principalPerm.Demand();
            Console.WriteLine("Demand succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    [PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]
    static void CheckAdministrator()
    {
        Console.WriteLine("User is an administrator");
    }
}

Remarks

Demand, InheritanceDemand, and LinkDemand are the only values of SecurityAction that have meaning for this attribute. Other actions do not apply to permissions that are not code access permissions.

Applies to

Производ Верзије (Застарело)
.NET (8 (package-provided), 9 (package-provided), 10 (package-provided))
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1 (5, 6, 7, 8, 9, 10)