DnsPermissionAttribute Класс

Определение

Внимание!

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

Устанавливает разрешение на запрос сведений с DNS-серверов.

public ref class DnsPermissionAttribute sealed : System::Security::Permissions::CodeAccessSecurityAttribute
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)]
public sealed class DnsPermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)]
[System.Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId="SYSLIB0003", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public sealed class DnsPermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)]
[System.Serializable]
public sealed class DnsPermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute
[<System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)>]
type DnsPermissionAttribute = class
    inherit CodeAccessSecurityAttribute
[<System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)>]
[<System.Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId="SYSLIB0003", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
type DnsPermissionAttribute = class
    inherit CodeAccessSecurityAttribute
[<System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)>]
[<System.Serializable>]
type DnsPermissionAttribute = class
    inherit CodeAccessSecurityAttribute
Public NotInheritable Class DnsPermissionAttribute
Inherits CodeAccessSecurityAttribute
Наследование
Атрибуты

Примеры

В следующем примере используется DnsPermissionAttribute для применения декларативной безопасности к пользовательскому классу.

//Uses the DnsPermissionAttribute to restrict access only to those who have permission.

[DnsPermission(SecurityAction::Demand,Unrestricted=true)]
public ref class MyClass
{
public:
   static IPAddress^ GetIPAddress()
   {
      IPAddress^ ipAddress = Dns::Resolve( "localhost" )->AddressList[ 0 ];
      return ipAddress;
   }

};

int main()
{
   try
   {
      
      //Grants Access.
      Console::WriteLine( " Access granted\n The local host IP Address is :{0}", MyClass::GetIPAddress() );
   }
   // Denies Access.
   catch ( SecurityException^ securityException ) 
   {
      Console::WriteLine( "Access denied" );
      Console::WriteLine( securityException->ToString() );
   }

}
public class MyClass
{
    public static IPAddress GetIPAddress()
    {
        IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
        return ipAddress;
    }
    public static void Main()
    {
        try
        {
            //Grants Access.
            Console.WriteLine(" Access granted\n The local host IP Address is :" +
                                  MyClass.GetIPAddress().ToString());
        }
        // Denies Access.
        catch (SecurityException securityException)
        {
            Console.WriteLine("Access denied");	
            Console.WriteLine(securityException.ToString());
        }
    }
}
' Uses the DnsPermissionAttribute to restrict access only to those who have permission.
<DnsPermission(SecurityAction.Demand, Unrestricted := true)>  _
Public Class MyClass1
   
   Public Shared Function GetIPAddress() As IPAddress
      Dim ipAddress As IPAddress = Dns.Resolve("localhost").AddressList(0)
      Return ipAddress
   End Function 'GetIPAddress
   
   Public Shared Sub Main()
      Try
         ' Grants Access.
         Console.WriteLine(("Access granted" + ControlChars.NewLine + " The local host IP Address is :" + MyClass1.GetIPAddress().ToString()))
      ' Denies Access.
      Catch securityException As SecurityException
         Console.WriteLine("Access denied")
         Console.WriteLine(securityException.ToString())
      End Try
   End Sub
End Class

Комментарии

Внимание!

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

Сведения о безопасности, объявленные параметром DnsPermissionAttribute , хранятся в метаданных целевого атрибута, который является классом DnsPermissionAttribute , к которому применяется . Затем система обращается к этой информации во время выполнения. Объект , SecurityAction передаваемый конструктору, определяет допустимые целевые объекты DNS.

Эти атрибуты безопасности используются только для декларативной безопасности. Для императивной безопасности используйте соответствующий DnsPermission класс .

Доступ к системе безопасности либо полностью ограничен, либо полностью не ограничен. Присвойте свойству Unrestricted значение true , чтобы предоставить доступ, или false для отсутствия доступа. Задайте это свойство как именованный параметр.

Дополнительные сведения об использовании атрибутов см. в разделе Атрибуты.

Конструкторы

DnsPermissionAttribute(SecurityAction)
Устаревшие..

Инициализирует новый экземпляр класса DnsPermissionAttribute заданным значением SecurityAction.

Свойства

Action
Устаревшие..

Возвращает или задает действие по обеспечению безопасности.

(Унаследовано от SecurityAttribute)
TypeId
Устаревшие..

В случае реализации в производном классе возвращает уникальный идентификатор для этого атрибута Attribute.

(Унаследовано от Attribute)
Unrestricted
Устаревшие..

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

(Унаследовано от SecurityAttribute)

Методы

CreatePermission()
Устаревшие..

Создает и возвращает новый экземпляр класса DnsPermission.

Equals(Object)
Устаревшие..

Возвращает значение, показывающее, равен ли экземпляр указанному объекту.

(Унаследовано от Attribute)
GetHashCode()
Устаревшие..

Возвращает хэш-код данного экземпляра.

(Унаследовано от Attribute)
GetType()
Устаревшие..

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
IsDefaultAttribute()
Устаревшие..

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.

(Унаследовано от Attribute)
Match(Object)
Устаревшие..

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

(Унаследовано от Attribute)
MemberwiseClone()
Устаревшие..

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()
Устаревшие..

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)
Устаревшие..

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации.

(Унаследовано от Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)
Устаревшие..

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

(Унаследовано от Attribute)
_Attribute.GetTypeInfoCount(UInt32)
Устаревшие..

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)
Устаревшие..

Предоставляет доступ к открытым свойствам и методам объекта.

(Унаследовано от Attribute)

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

См. также раздел