如何:通过使用 RequestMinimum 标志请求最小权限

更新:2007 年 11 月

利用 RequestMinimum 标志,可以请求执行代码所需的一组最小权限。相反,RequestRefuse 标志允许您通过明确指定不应该向您的代码授予哪些权限来拒绝权限。

与使用 RequestMinimum 标志相比,如果应用程序没有接收到使用 RequestOptional 标志请求的所有权限,则您的应用程序将执行,当该应用程序试图访问受保护的资源时,将引发 SecurityException。如果您使用此类型的请求,必须使您的代码能够捕捉在未授予代码可选权限的情况下引发的任何异常。

下面的示例使用 RequestMinimum 标志请求 FileIOPermission。如果尚未被授予请求的权限,此示例将不会执行。此示例假定在 LogNameSpace 中存在一个假设的类 Log。Log 类包含可在本地计算机上创建新的日志文件的 MakeLog 方法。此应用程序创建 Log 类的一个新实例,并在 try 块中执行 MakeLog 方法。使用 catch 关键字,它可以截获引发的任何 SecurityException 并显示消息。

示例

Imports System
Imports System.Security
'The hypothetical class log is in this namespace.
Imports LogNameSpace
Imports System.Security.Permissions
'The request is placed at the assembly level.
<assembly: FileIOPermission(SecurityAction.RequestMinimum, Unrestricted := True)>

Namespace MyNamespace
   Public Class MyClass1
      
      Public Sub New()

      End Sub
      
      'Entry point that delegates to C-style main Private Function.
      Public Overloads Shared Sub Main()
         Main(System.Environment.GetCommandLineArgs())
      End Sub
      
      Overloads Public Shared Sub Main(args() As String)
         'Put any code that requires optional permissions in the try block. 
         Try
            Dim MyLog As New Log()
            MyLog.MakeLog()
            Console.WriteLine("The Log has been created.")
         'Catch the security exception and inform the user that the 
         'application was not granted FileIOPermission.
         Catch
            Console.WriteLine("This application does not have permission to write to the disk.")
         End Try
      End Sub
   End Class
End Namespace     
//The request is placed at the assembly level.
using System.Security.Permissions;
[assembly:FileIOPermission(SecurityAction.RequestMinimum, Unrestricted = true)]

namespace MyNamespace {
   using System;
   using System.Security;
   //The hypothetical class log is in this namespace.
   using LogNameSpace;

   public class MyClass {
      public MyClass() {
      }

      public static void Main(string[] args) {
         //Put any code that requires optional permissions in the try block. 
         try {
            Log MyLog = new Log();
            MyLog.MakeLog();
            Console.WriteLine("The Log has been created.");
         }
         //Catch the security exception and inform the user that the 
         //application was not granted FileIOPermission.
         catch(SecurityException) {
            Console.WriteLine("This application does not have permission to write to the disk.");
         }
      }
   }
}

如果上面的代码有足够的权限,它会创建日志文件并将下面的消息显示到控制台上:

The Log has been created.

如果从共享位置运行该代码,并且本地安全设置不允许此类代码拥有 FileIOPermission,则不会授予该代码足够的权限,并显示下面的消息:

This application does not have permission to write to the disk.

请参见

概念

请求权限

参考

SecurityAction

FileIOPermission

UIPermission

其他资源

利用属性扩展元数据

代码访问安全性