SecurityAction Enumeração

Definição

Cuidado

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

Cuidado

CAS support is not available with Silverlight applications.

Especifica as ações de segurança que podem ser executadas usando a segurança 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
Herança
SecurityAction
Atributos

Campos

Assert 3

O código de chamada pode acessar o recurso identificado pelo objeto de permissão atual, mesmo que os chamadores na pilha não tenham recebido permissão para acessar o recurso (consulte Usando o Método Assert).

Demand 2

Todos os chamadores na pilha de chamadas deverão ter a permissão especificada pelo objeto de permissão atual.

Deny 4

A capacidade de acessar o recurso especificado pelo objeto de permissão atual é negado aos chamadores, mesmo que eles tenham recebido permissão para acessá-lo (consulte Usando o Método Deny).

InheritanceDemand 7

A classe derivada que está herdando a classe ou substituindo um método deverá ter recebido a permissão especificada.

LinkDemand 6

O chamador imediato deverá ter recebido a permissão especificada. Não use no .NET Framework 4. Para confiança total, use SecurityCriticalAttribute; para confiança parcial, use Demand.

PermitOnly 5

Somente os recursos especificados por esse objeto de permissão poderão ser acessados, mesmo que o código tenha recebido permissão para acessar outros recursos.

RequestMinimum 8

A solicitação para as permissões mínimas necessárias para a execução do código. Esta ação só pode ser usada no escopo do assembly.

RequestOptional 9

A solicitação de permissões adicionais que são opcionais (não necessárias para a execução). Essa solicitação recusa implicitamente todas as outras permissões não solicitadas especificamente. Esta ação só pode ser usada no escopo do assembly.

RequestRefuse 10

A solicitação de permissões que podem ser usadas indevidamente não serão concedidas ao código de chamada. Esta ação só pode ser usada no escopo do assembly.

Exemplos

Este exemplo mostra como notificar o CLR de que o código em métodos chamados tem apenas IsolatedStoragePermission, e também demonstra como gravar e ler do armazenamento isolado.

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.

Comentários

Cuidado

O CAS (Code Access Security) foi preterido em todas as versões do .NET Framework e do .NET. As versões recentes do .NET não respeitam as anotações CAS e produzem erros se AS APIs relacionadas ao CAS forem usadas. Os desenvolvedores devem buscar meios alternativos de realizar tarefas de segurança.

A tabela a seguir descreve a hora em que cada ação de segurança ocorre e os destinos aos quais ela dá suporte.

Importante

No .NET Framework 4, o suporte ao runtime foi removido para impor as solicitações de permissão Deny, RequestMinimum, RequestOptional e RequestRefuse. Essas solicitações não devem ser usadas no código baseado em .NET Framework 4 ou posterior. Para obter mais informações sobre essa e outras alterações, consulte Alterações de Segurança.

Você não deve usar LinkDemand no .NET Framework 4. Em vez disso, use o para restringir o SecurityCriticalAttribute uso a aplicativos totalmente confiáveis ou usar Demand para restringir chamadores parcialmente confiáveis.

Declaração de ação de segurança Tempo de ação Destinos com suporte
LinkDemand(não use no .NET Framework 4) Compilação just-in-time Classe, método
InheritanceDemand Tempo de carregamento Classe, método
Demand Tempo de execução Classe, método
Assert Tempo de execução Classe, método
Deny(obsoleto no .NET Framework 4) Tempo de execução Classe, método
PermitOnly Tempo de execução Classe, método
RequestMinimum(obsoleto no .NET Framework 4) Tempo de concessão Assembly
RequestOptional(obsoleto no .NET Framework 4) Tempo de concessão Assembly
RequestRefuse(obsoleto no .NET Framework 4) Tempo de concessão Assembly

Para obter informações adicionais sobre destinos de atributo, consulte Attribute.

Aplica-se a