加入宣告式安全性支援

雖然並非絕對需要,自訂使用權限仍應該支援宣告式安全性,使開發人員在使用安全性動作 (如要求、需求或判斷提示) 的宣告式語法時,仍可以指定自訂使用權限。 事實上,使用權限要求、連結要求和繼承要求也只能利用宣告式來設定。 因此,在您提供宣告式安全性支援之前,連結要求或繼承要求中都不可以要求或使用自訂程式碼存取使用權限。 這個主題將說明如何實作一個 Attribute 類別,提供自訂使用權限的宣告式安全性支援。

注意事項注意事項

自訂權限的屬性版本必須在組件中定義,但該組件不得參考該屬性版本。自訂權限也應在該組件中定義。這對宣告式安全性來說是必要的,因為屬性會在組件載入時執行,而該屬性的參考發生時,屬性可能尚未建立。嘗試在定義宣告式權限的同一個組件中使用該權限,會導致擲回 TypeLoadException

宣告的安全性屬性必須衍生 (直接或間接) 自 SecurityAttribute 類別。 如果使用權限是程式碼存取使用權限,則屬性類別會衍生自 CodeAccessSecurityAttribute,後者本身則是衍生自 SecurityAttribute。 安全性屬性類別必須實作 CreatePermission 方法,以從關聯的自訂使用權限中建立使用權限物件的執行個體。 請注意,此關聯的自訂使用權限類別必須使用 SerializableAttribute 標記,讓編譯器將其序列化為中繼資料。 如需詳細資訊,請參閱實作自訂使用權限

下列程式碼對名為 CustomPermission 的 Boolean 使用權限實作屬性類別。 在這個範例中,使用權限類別具有一個包含其狀態的單一 Boolean Unrestricted 屬性。

<AttributeUsageAttribute(AttributeTargets.All, AllowMultiple := True)> Public Class 
CustomPermissionAttribute

   Inherits CodeAccessSecurityAttribute
   Private myUnrestricted As Boolean = False
   
   Public Shadows Property Unrestricted() As Boolean
      Get
         Return myUnrestricted
      End Get
      Set
         myUnrestricted = value
      End Set
   End Property
    
   Public Sub New(action As SecurityAction)
      MyBase.New(action)
   End Sub
   
   Public Overrides Function CreatePermission() As IPermission
      If Unrestricted Then
         Return New CustomPermission(PermissionState.Unrestricted)
      Else
         Return New CustomPermission(PermissionState.None)
      End If
   End Function
End Class
[AttributeUsageAttribute(AttributeTargets.All, AllowMultiple = true)]
public class CustomPermissionAttribute: CodeAccessSecurityAttribute
{
   bool unrestricted = false;

   public new bool Unrestricted
   {
      get{ return unrestricted; }
      set{ unrestricted = value; }
   }

   public CustomPermissionAttribute(SecurityAction action): base (action)
   {  
   }
   public override IPermission CreatePermission()
   {
      if(Unrestricted)
      {
         return new CustomPermission(PermissionState.Unrestricted);
      }
      else
      {
         return new CustomPermission(PermissionState.None);
      }
   }
}

在這個範例中,CreatePermission 會檢查內部 Unrestricted 屬性,並建立適當的 CustomPermission 物件執行個體。 雖然在這個範例中只使用 Unrestricted 屬性,其他的自訂使用權限屬性類別仍可支援其本身所支援使用權限物件的所有可能狀態。

以下要求宣告將說明 CustomPermissionAttribute 的用法:

<CustomPermissionAttribute(SecurityAction.Demand, Unrestricted := true)>
[CustomPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]

請參閱

參考

SecurityAttribute

CodeAccessSecurityAttribute

SerializableAttribute

概念

建立您自己的程式碼存取使用權限

實作自訂使用權限

其他資源

使用屬性擴充中繼資料

程式碼存取安全性