【问题标题】:Postsharp compile-time validation on interface methods接口方法的 Postsharp 编译时验证
【发布时间】:2013-05-13 11:44:48
【问题描述】:

我有一个包含服务合同的程序集(程序集名称是 Contracts)。我想使用属性和 PostSharp 对这些方法实施授权。 授权属性如下所示:

public class Auth : System.Attribute 
{
    public Auth(String permission){...}
}

我希望我的服务合同如下所示:

namespace Contracts
{
    public interface IService
    {
        [Auth("CanCallFoo")]
        void Foo();
    }
}


我想在编译时检查 Contracts 程序集中接口中的所有方法是否具有 Auth 属性。
为此,我创建了以下方面:

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Interface & MulticastTargets.Method)]
public class EnforceSecurityAspect : OnMethodBoundaryAspect
{
    public override bool CompileTimeValidate(System.Reflection.MethodBase method)
    {
        var hasSecurityAttribute = method.GetCustomAttributes(true).Any(x => x is Auth);
        if (!hasSecurityAttribute)
        {
            throw new InvalidAnnotationException(String.Format("Add `Auth` to `{0}`", method.Name));
        }

        return base.CompileTimeValidate(method);
    }
}

我在 Contracts 程序集的 AssemblyInfo 中使用这行代码应用方面:

[assembly: EnforceSecurityAspect()]

在同一个程序集中,我还拥有服务使用的 DTO。
我面临的问题是方面也适用于 DTO
例如我有一个像这样的 DTO

public class Client
{
    public String Name{get;set;}
}

在编译时我收到一个错误,说我应该将Auth 添加到编译器生成的get_Name 方法中。
问:有没有办法告诉 Postsharp 方面应该只适用于接口的方法?

【问题讨论】:

    标签: .net aop postsharp


    【解决方案1】:

    我知道这是一个老问题,但我想为遇到此问题的任何人提供一个答案。

    虽然可以使用特定的目标来继承/实现带有 postsharp 的某个接口/类,但我不知道如何。

    解决方案是创建一个方面并以类为目标(还没有这样做,但我确定它是可能的)。然后,您可以使用反射仅使用Type 上可用的方法验证从某个类/接口继承的类,例如FindInterfaces

    使用与以下代码类似的东西。 (注意这是 postsharp Enterprice 功能)

    [MulticastAttributeUsage(MulticastTargets.Class)]
    public class MulticastTest : MulticastAttribute, IScalarConstraint
    {
        public void ValidateCode(object target)
        {
            throw new NotImplementedException();
        }
    
        public bool ValidateConstraint(object target)
        {
            var type = target.GetType();
            Console.Write(type.Name);//Actually do something here
            return true;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多