【发布时间】: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 方面应该只适用于接口的方法?
【问题讨论】: