< Day Day Up > |
TechniqueThe technique is similar to that for applying security attributes to an assembly: You simply apply the same attributes to the relevant class or method instead. In this case, the security requests are processed the first time that the class or the method is used. However, the allowed security actions for a class or method are different. For a class or method, you can request the security actions in Table 21.3. Table 21.3. SecurityAction Values for a Class or Method
A couple of examples will illustrate this technique. The following code shows a method that needs permission to read the D:\ drive on the file system: [FileIOPermission(SecurityAction.Demand, Read=@"D:\")] public string [] ListDDriveFolders() { The next code is a class that often invokes unsafe code but has been thoroughly tested so we are sure it is sufficiently safe to assert this permission: [SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)] public class SafeClass { CommentsWhen applying permissions to methods, you have a choice between using declarative and imperative security. The advantage of using declarative security is that it is often simpler to code and can lead to higher performance because you can perform the security checks when an assembly is loaded. You also benefit from the extra information because the declarative security is visible through the assembly metadata. Note, however, that this benefit is not that significant for classes and methods because using that information requires an understanding of the classes and methods in an assembly. In addition, permview only displays security attributes applied to the assembly as a whole. Declarative security does allow a couple of security actions that you cannot accomplish using imperative security. Imperative security does not contain any analogy to the link demand or the inheritance demand, so if you want to enforce those actions, you have no choice but to use declarative security. |
< Day Day Up > |