声明性安全

声明式安全性语法使用特性来将安全信息放到代码的元数据中。 可以将特性放在程序集、类或成员级别,来指示您要使用的请求、要求或重写的类型。 在以公共语言运行时为目标的应用程序中,请求用于通知运行时安全系统应用程序需要或不需要的权限。 要求和重写在库中用来帮助防止调用方调用资源或重写默认安全行为。

注意注意

在 .NET Framework 4 版中,对 .NET Framework 安全模型和术语进行了重要的更改。有关这些更改的更多信息,请参见 .NET Framework 4 中的安全性更改

为了使用声明式安全调用,您必须初始化权限对象的状态数据,使之表示您需要的特定形式的权限。 每个内置权限都具有一个特定特性,通过向该特性传递 SecurityAction 枚举可描述要执行的安全操作的类型。 但是,权限还接受它们自己的独占参数。 有关权限特定的参数的完整说明,请参见描述内置权限的部分。

下面的代码段说明声明式语法,该语法用于请求代码的调用方拥有名为 MyPermission 的自定义权限。 此权限是假设的自定义权限,在 .NET Framework 中并不存在。 在此示例中,声明式调用直接放在类定义之前,指定将此权限应用到类级别。 向该特性传递一个 SecurityAction.Demand 结构来指定调用方必须拥有此权限才能运行。

<MyPermission(SecurityAction.Demand, Unrestricted = True)> Public Class MyClass1
   
   Public Sub New()
      'The constructor is protected by the security call.
   End Sub
   
   
   Public Sub MyMethod()
      'This method is protected by the security call.
   End Sub
   
   
   Public Sub YourMethod()
      'This method is protected by the security call.
   End Sub
End Class
[MyPermission(SecurityAction.Demand, Unrestricted = true)]
public class MyClass
{
   public MyClass()
   {
      //The constructor is protected by the security call.
   }

   public void MyMethod()
   {
      //This method is protected by the security call.
   }

   public void YourMethod()
   {
      //This method is protected by the security call.
   }
}

请参见

参考

SecurityAction

概念

利用特性扩展元数据

安全性语法

代码访问安全性

元数据和自描述组件

安全权限