SecurityAction Enumeración

Definición

Precaución

Code Access Security is not supported or honored by the runtime.

Precaución

CAS support is not available with Silverlight applications.

Especifica las acciones de seguridad que se pueden realizar mediante la seguridad declarativa.

public enum class SecurityAction
[System.Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId="SYSLIB0003", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public enum SecurityAction
public enum SecurityAction
[System.Serializable]
public enum SecurityAction
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum SecurityAction
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Obsolete("CAS support is not available with Silverlight applications.")]
public enum SecurityAction
[<System.Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId="SYSLIB0003", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
type SecurityAction = 
type SecurityAction = 
[<System.Serializable>]
type SecurityAction = 
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type SecurityAction = 
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Obsolete("CAS support is not available with Silverlight applications.")>]
type SecurityAction = 
Public Enum SecurityAction
Herencia
SecurityAction
Atributos

Campos

Assert 3

El código de llamada puede tener acceso al recurso identificado por el objeto de permiso actual, incluso si los autores de la llamada situados en una posición más alta de la pila no tienen permiso para tener acceso al recurso (vea Uso del método Assert).

Demand 2

Todos los autores de llamada de la pila necesitan que se les conceda el permiso especificado por el objeto de permiso actual.

Deny 4

La posibilidad de acceder al recurso especificado por el objeto de permiso actual se deniega a los llamadores, incluso si a estos se les ha concedido acceso al recurso (consulte Utilizar el método Deny).

InheritanceDemand 7

La clase derivada que hereda la clase o que reemplaza un método debe tener el permiso especificado.

LinkDemand 6

Es necesario que el llamador inmediato haya recibido el permiso especificado. No use en .NET Framework 4. Para la confianza completa, use SecurityCriticalAttribute; para la confianza parcial, use Demand.

PermitOnly 5

Solo se puede acceder a los recursos especificados por este objeto de permiso, aunque al código se le haya concedido permiso de acceso a otros recursos.

RequestMinimum 8

Solicitud de los permisos mínimos necesarios para que se ejecute el código. Esta acción solo se puede usar en el ámbito del ensamblado.

RequestOptional 9

Solicitud de permisos adicionales que son opcionales (no es necesaria la ejecución). Esta solicitud rechaza implícitamente todos los demás permisos no solicitados específicamente. Esta acción solo se puede usar en el ámbito del ensamblado.

RequestRefuse 10

Solicitud de que al código de llamada no se le concedan permisos que se puedan usar indebidamente. Esta acción solo se puede usar en el ámbito del ensamblado.

Ejemplos

En este ejemplo se muestra cómo notificar al CLR que el código de los métodos llamados solo IsolatedStoragePermissiontiene y también muestra cómo escribir y leer desde el almacenamiento aislado.

using namespace System;
using namespace System::Security;
using namespace System::Security::Permissions;
using namespace System::IO::IsolatedStorage;
using namespace System::IO;


static void WriteIsolatedStorage()
{
    try
    {
        // Attempt to create a storage file that is isolated by
        // user and assembly. IsolatedStorageFilePermission
        // granted to the attribute at the top of this file
        // allows CLR to load this assembly and execution of this
        // statement.
        Stream^ fileCreateStream = gcnew
            IsolatedStorageFileStream(
            "AssemblyData",
            FileMode::Create,
            IsolatedStorageFile::GetUserStoreForAssembly());

        StreamWriter^ streamWriter = gcnew StreamWriter(
            fileCreateStream);
        try
        {
            // Write some data out to the isolated file.

            streamWriter->Write("This is some test data.");
            streamWriter->Close();	
        }
        finally
        {
            delete fileCreateStream;
            delete streamWriter;
        } 
    }
    catch (IOException^ ex)
    {
        Console::WriteLine(ex->Message);
    }

    try
    {
        Stream^ fileOpenStream =
            gcnew IsolatedStorageFileStream(
            "AssemblyData",
            FileMode::Open,
            IsolatedStorageFile::GetUserStoreForAssembly());
        // Attempt to open the file that was previously created.

        StreamReader^ streamReader = gcnew StreamReader(
            fileOpenStream);
        try
        { 
            // Read the data from the file and display it.

            Console::WriteLine(streamReader->ReadLine());
            streamReader->Close();
        }
        finally
        {
            delete fileOpenStream;
            delete streamReader;
        }
    }
    catch (FileNotFoundException^ ex)
    {
        Console::WriteLine(ex->Message);
    }
    catch (IOException^ ex)
    {
        Console::WriteLine(ex->Message);
    }
}
// Notify the CLR to only grant IsolatedStorageFilePermission to called methods. 
// This restricts the called methods to working only with storage files that are isolated 
// by user and assembly.
[IsolatedStorageFilePermission(SecurityAction::PermitOnly, UsageAllowed = IsolatedStorageContainment::AssemblyIsolationByUser)]
int main()
{
    WriteIsolatedStorage();
}

// This code produces the following output.
//
//  This is some test data.
using System;
using System.Security.Permissions;
using System.IO.IsolatedStorage;
using System.IO;

// Notify the CLR to only grant IsolatedStorageFilePermission to called methods.
// This restricts the called methods to working only with storage files that are isolated
// by user and assembly.
[IsolatedStorageFilePermission(SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser)]
public sealed class App
{
    static void Main()
    {
        WriteIsolatedStorage();
    }
    private static void WriteIsolatedStorage()
    {
        // Attempt to create a storage file that is isolated by user and assembly.
        // IsolatedStorageFilePermission granted to the attribute at the top of this file
        // allows CLR to load this assembly and execution of this statement.
        using (Stream s = new IsolatedStorageFileStream("AssemblyData", FileMode.Create, IsolatedStorageFile.GetUserStoreForAssembly()))
        {

            // Write some data out to the isolated file.
            using (StreamWriter sw = new StreamWriter(s))
            {
                sw.Write("This is some test data.");
            }
        }

        // Attempt to open the file that was previously created.
        using (Stream s = new IsolatedStorageFileStream("AssemblyData", FileMode.Open, IsolatedStorageFile.GetUserStoreForAssembly()))
        {
            // Read the data from the file and display it.
            using (StreamReader sr = new StreamReader(s))
            {
                Console.WriteLine(sr.ReadLine());
            }
        }
    }
}

// This code produces the following output.
//
//  Some test data.
Option Strict On
Imports System.Security.Permissions
Imports System.IO.IsolatedStorage
Imports System.IO


' Notify the CLR to only grant IsolatedStorageFilePermission to called methods. 
' This restricts the called methods to working only with storage files that are isolated 
' by user and assembly.
<IsolatedStorageFilePermission(SecurityAction.PermitOnly, UsageAllowed:=IsolatedStorageContainment.AssemblyIsolationByUser)> _
Public NotInheritable Class App

    Shared Sub Main()
        WriteIsolatedStorage()
    End Sub
    Shared Sub WriteIsolatedStorage()
        ' Attempt to create a storage file that is isolated by user and assembly.
        ' IsolatedStorageFilePermission granted to the attribute at the top of this file 
        ' allows CLR to load this assembly and execution of this statement.
        Dim s As New IsolatedStorageFileStream("AssemblyData", FileMode.Create, IsolatedStorageFile.GetUserStoreForAssembly())
        Try

            ' Write some data out to the isolated file.
            Dim sw As New StreamWriter(s)
            Try
                sw.Write("This is some test data.")
            Finally
                sw.Dispose()
            End Try
        Finally
            s.Dispose()
        End Try

        ' Attempt to open the file that was previously created.
        Dim t As New IsolatedStorageFileStream("AssemblyData", FileMode.Open, IsolatedStorageFile.GetUserStoreForAssembly())
        Try
            ' Read the data from the file and display it.
            Dim sr As New StreamReader(t)
            Try
                Console.WriteLine(sr.ReadLine())
            Finally
                sr.Dispose()
            End Try
        Finally
            t.Dispose()
        End Try

    End Sub
End Class

' This code produces the following output.
'
'  Some test data.

Comentarios

Precaución

La seguridad de acceso del código (CAS) ha quedado en desuso en todas las versiones de .NET Framework y .NET. Las versiones recientes de .NET no respetan las anotaciones de CAS y generan errores si se usan API relacionadas con CAS. Los desarrolladores deben buscar medios alternativos para realizar tareas de seguridad.

En la tabla siguiente se describe el tiempo que tiene lugar cada acción de seguridad y los destinos que admite.

Importante

En .NET Framework 4, se ha quitado la compatibilidad en tiempo de ejecución para aplicar las solicitudes de permisos Deny, RequestMinimum, RequestOptional y RequestRefuse. Estas solicitudes no se deben usar en el código basado en .NET Framework 4 o posterior. Para obtener más información sobre este y otros cambios, consulte Cambios de seguridad.

No debe usar LinkDemand en .NET Framework 4. En su lugar, use para restringir el SecurityCriticalAttribute uso de aplicaciones de plena confianza o para Demand restringir los autores de llamadas de confianza parcial.

Declaración de acción de seguridad Hora de acción Destinos admitidos
LinkDemand (no use en .NET Framework 4) Compilación Just-In-Time Clase, método
InheritanceDemand Tiempo de carga Clase, método
Demand Tiempo de ejecución Clase, método
Assert Tiempo de ejecución Clase, método
Deny (obsoleto en .NET Framework 4) Tiempo de ejecución Clase, método
PermitOnly Tiempo de ejecución Clase, método
RequestMinimum (obsoleto en .NET Framework 4) Tiempo de concesión Ensamblado
RequestOptional (obsoleto en .NET Framework 4) Tiempo de concesión Ensamblado
RequestRefuse (obsoleto en .NET Framework 4) Tiempo de concesión Ensamblado

Para obtener información adicional sobre los destinos de atributo, vea Attribute.

Se aplica a