c# - 使用实例成员发布尖锐

标签 c# postsharp

我正在尝试创建一个方面来管理类的一些属性的安全性。但是,一个成员的安全方面依赖于类的另一个属性中的数据。我已经阅读了一些关于 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/

相关文章:

c# - 使用 web.config 授权元素时未触发 OWIN 质询

C# - 在 js 中访问 activeX 控件的简单属性时出错 - stackoverflowexception

java - AspectJ 和 PostSharp 之间的功能差异是什么?

c# - 使用这种异步日志记录代码有什么缺点?

c# - 带有 postsharp 2.0 的 Log4Postsharp(死了?)还是放弃了 ELMAH?

c# - Mono Assembly 未解决

C# 替换多个 href 值

c# - 如何在 C# 中使用 System.Reflection.MethodBase 查找方法的返回类型?

c# - 如何将 postsharp 方面应用于网站项目?

c# - list Remove 方法不会删除列表项