如何检查是否C#类使用了安全属性 [英] How to check if C# class has security attribute used
问题描述
如何检查,确保一类使用自己的自定义安全属性?我知道我可以使用反射来获得正常的属性,但是如果自定义属性是基于安全属性如下图所示反射不显示它。有没有什么办法来检查?
How can I check and make sure that a class uses my own custom security attribute? I know that I can use reflection to get normal attributes, but if the custom attribute is based on a security attribute as shown below reflection doesn't show it. Is there any way to check that?
为什么我需要这是为了确保被加载到基于云的系统中的插件必须使用安全属性,因此该类。是那些获得的加载不能访问任何限制的文件等等。
Why I would need this is to make sure that a plugin that is loaded to a cloud based system must use security attribute so the class that get's loaded cannot access any restricted files and so on.
下面是我使用的自定义安全类:
Here is the custom security class I'm using:
public class PluginSection : CodeAccessSecurityAttribute
{
public PluginSection(SecurityAction action)
: base(action)
{
}
public override IPermission CreatePermission()
{
// WebSites.GetInstance().LocalBaseDir returns the base directory where the class has accesss to login
return new FileIOPermission(FileIOPermissionAccess.Write, WebSites.GetInstance().LocalBaseDir);
}
}
我必须使用基于一类CodeAccessSecurityAttribute这样的FileIOPermission会工作。
I must use a class based on CodeAccessSecurityAttribute so that the FileIOPermission would work.
此外,如果有另一种方式来限制插件的访问被加载,我可以用这一点。
Also if there is another way to restrict the access of the plugin being loaded I could use that too.
推荐答案
反射似乎为我工作的罚款:
Reflection seems to work fine for me:
using System;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
public class PluginSection : CodeAccessSecurityAttribute
{
public PluginSection(SecurityAction action)
: base(action)
{
}
public override IPermission CreatePermission()
{
// Removed for demo purposes
return null;
}
}
class NotApplied {}
[PluginSection(SecurityAction.Demand)]
class Applied{}
class Test
{
static void Main()
{
Console.WriteLine(IsPluginSection(typeof(Applied)));
Console.WriteLine(IsPluginSection(typeof(NotApplied)));
}
static bool IsPluginSection(Type type)
{
return type.IsDefined(typeof(PluginSection), false)
}
}
这篇关于如何检查是否C#类使用了安全属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!