SecurityAction Перечисление

Определение

Внимание!

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

Внимание!

CAS support is not available with Silverlight applications.

Указывает действия безопасности, которые можно выполнить с помощью декларативной безопасности.

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
Наследование
SecurityAction
Атрибуты

Поля

Assert 3

Вызывающий код может получить доступ к ресурсу, определяемому текущим объектом разрешения, даже если вызывающим объектам выше в стеке вызовов не предоставлено разрешение на доступ к ресурсу (см. раздел Использование метода Assert).

Demand 2

Всем вызывающим объектам выше в стеке вызовов должно быть предоставлено разрешение, заданное текущим объектом разрешений.

Deny 4

Вызывающим объектам запрещен доступ к ресурсу (определяется текущим объектом разрешения), даже если им предоставлено разрешение на доступ к этому ресурсу (см. раздел об использовании метода Deny).

InheritanceDemand 7

Необходимо, чтобы производному классу, наследующему класс или переопределяющему метод, было предоставлено указанное разрешение.

LinkDemand 6

Указанное разрешение необходимо предоставить непосредственно вызывающему объекту. Не используйте в платформа .NET Framework 4. Для полного доверия используйте вместо него SecurityCriticalAttribute; для частичного доверия используйте Demand.

PermitOnly 5

Доступ можно получить только к ресурсам, указанным данным объектом разрешения, даже если коду предоставлено разрешение на доступ к другим ресурсам.

RequestMinimum 8

Запрос на минимальный набор разрешений, необходимых для выполнения кода. Это действие может использоваться только в пределах сборки.

RequestOptional 9

Запрос дополнительных разрешений, которые не являются обязательными (не требуются для выполнения). Этот запрос неявно отклоняет все прочие разрешения, не запрошенные специально. Это действие может использоваться только в пределах сборки.

RequestRefuse 10

Запрос на непредоставление вызывающему коду разрешений, которые могут быть неправильно использованы. Это действие может использоваться только в пределах сборки.

Примеры

В этом примере показано, как уведомить среду CLR о том, что код в вызываемых методах содержит только IsolatedStoragePermission, а также демонстрирует запись и чтение из изолированного хранилища.

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.

Комментарии

Внимание!

Безопасность доступа к коду (CAS) не рекомендуется использовать во всех версиях платформа .NET Framework и .NET. В последних версиях .NET заметки CAS не учитываются и при использовании API, связанных с CAS, возникают ошибки. Разработчикам следует искать альтернативные средства для выполнения задач безопасности.

В следующей таблице описывается время выполнения каждого действия по обеспечению безопасности и поддерживаемые им целевые объекты.

Важно!

В платформа .NET Framework 4 поддержка среды выполнения была удалена для применения запросов разрешений Deny, RequestMinimum, RequestOptional и RequestRefuse. Эти запросы не следует использовать в коде, основанном на платформа .NET Framework 4 или более поздней версии. Дополнительные сведения об этих и других изменениях см. в разделе Изменения системы безопасности.

Не следует использовать LinkDemand в платформа .NET Framework 4. Вместо этого используйте SecurityCriticalAttribute , чтобы ограничить использование полностью доверенными приложениями, или используйте для Demand ограничения частично доверенных вызывающих объектов.

Объявление действий по обеспечению безопасности Время действия Поддерживаемые целевые объекты
LinkDemand(не используйте в платформа .NET Framework 4) JIT-компиляция Класс, метод
InheritanceDemand Время загрузки Класс, метод
Demand Во время выполнения Класс, метод
Assert Во время выполнения Класс, метод
Deny(устарело в платформа .NET Framework 4) Во время выполнения Класс, метод
PermitOnly Во время выполнения Класс, метод
RequestMinimum(устарело в платформа .NET Framework 4) Время предоставления Сборка
RequestOptional(устарело в платформа .NET Framework 4) Время предоставления Сборка
RequestRefuse(устарело в платформа .NET Framework 4) Время предоставления Сборка

Дополнительные сведения о целевых объектах атрибутов см. в разделе Attribute.

Применяется к