我正在尝试创建一个方面来管理类的一些属性的安全性。但是,一个成员的安全方面依赖于类的另一个属性中的数据。我已经阅读了一些关于 IntroduceAspect 的教程,但我不确定它是否是我需要的。
public class ClassWithThingsIWantToSecure
{
[SecurityAspectHere(inherits from LocationInterceptionAspect)]
public int ThingIWantToSecure;
public string ThingINeedToKnowAboutInSecurityAspect;
}
有人可以指出正确的方向,使 ThingINeedToKnowAboutInSecurityAspect 的运行时值在 SecurityAspect 中可用吗?
最佳答案
我以前做过类似的事情,我在一台安装了 postsharp 的机器上进行了测试并试了一下,这是代码...
class Program
{
static void Main(string[] args)
{
Baldrick baldrick = new Baldrick();
baldrick.ThingINeedToKnowAboutInSecurityAspect = "Bob";
Console.WriteLine("There are {0} beans", baldrick.ThingIWantToSecure);
baldrick.ThingINeedToKnowAboutInSecurityAspect = "Kate";
try
{
//This should fail
Console.WriteLine("There are {0} beans", baldrick.ThingIWantToSecure);
}
catch (Exception ex)
{
//Expect the message from my invalid operation exception to be written out (Use your own exception if you prefer)
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
[Serializable]
public class SecurityAspect : LocationInterceptionAspect
{
public override void OnGetValue(LocationInterceptionArgs args)
{
ISecurityProvider securityProvider = args.Instance as ISecurityProvider;
if (securityProvider != null && securityProvider.ThingINeedToKnowAboutInSecurityAspect != "Bob")
throw new InvalidOperationException("Access denied (or a better message would be nice!)");
base.OnGetValue(args);
}
}
public interface ISecurityProvider
{
string ThingINeedToKnowAboutInSecurityAspect { get; }
}
public class Baldrick : ISecurityProvider
{
public string ThingINeedToKnowAboutInSecurityAspect { get; set; }
[SecurityAspect]
public int ThingIWantToSecure{get { return 3; }}
}
因此,这里的想法是查询正在装饰的对象的实例的 args.Instance 属性。
关于c# - 使用实例成员发布尖锐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21269249/