C# Postsharp AOP方法拦截方面不工作
我试图添加一个基于权限的属性,供使用WPF构建的现有Windows应用程序使用。 其想法是拦截对某些命令的Canexecute方法的调用,并返回false,这将禁用按钮- 因此,我在一个解决方案上做了一个简单的示例,其中我添加了Postsharp的Nuget包,并覆盖了OnInvoke方法,如下所示:C# Postsharp AOP方法拦截方面不工作,c#,postsharp,method-interception,C#,Postsharp,Method Interception,我试图添加一个基于权限的属性,供使用WPF构建的现有Windows应用程序使用。 其想法是拦截对某些命令的Canexecute方法的调用,并返回false,这将禁用按钮- 因此,我在一个解决方案上做了一个简单的示例,其中我添加了Postsharp的Nuget包,并覆盖了OnInvoke方法,如下所示: [Serializable] public class PermissionBasedAttribute : MethodInterceptionAspect { public strin
[Serializable]
public class PermissionBasedAttribute : MethodInterceptionAspect
{
public string PermissionName { get; private set; }
public PermissionBasedAttribute (string permissionName)
{
PermissionName = permissionName;
}
/// <summary>
/// Upon invocation of the calling method, the PermissionName is checked.
/// If no exception is thrown, the calling method proceeds as normal.
/// If an exception is thrown, the virtual method MethodOnException is called.
/// </summary>
/// <seealso cref="MethodOnException(SecurityPermissionException)"/>
public override void OnInvoke(MethodInterceptionArgs args)
{
try
{
/*
* some logic to check the eligibility of the user, in case of
not authorised an exception should be thrown.
*/
args.Proceed();
}
catch (SecurityPermissionException ex)
{
args.ReturnValue = false;
// MethodOnException(ex);
}
}
/// <summary>
/// Method can be overridden in a derived attribute class.
/// Allows the user to handle the exception in whichever way they see fit.
/// </summary>
/// <param name="ex">The exception of type SecurityPermissionException</param>
public virtual void MethodOnException(SecurityPermissionException ex)
{
throw ex;
}
}
原来,后夏普是在这个项目中禁用!!!我安装了Post sharp扩展,然后转到Post sharp部分。我发现它被禁用了,一旦启用,效果就很好了。请您描述一下如何在应用程序的源代码中应用您的方面?我怀疑PostSharp无法找到该方面的任何有效目标。例如,如果您的类未实现CanExecute方法,则无法拦截该方法。也许对您来说,更好的方法是引入并覆盖CanExecute方法:我已经更新了这个问题,以包括如何使用它的示例。can执行是ICommand接口的一部分。它已经在处理这个简单的例子了。在现有应用程序编号上。此外,我已通过CompileTimeValidation检查以引发异常,但它仍然没有命中。好的,您确定此项目已执行PostSharp吗?也就是说,其他方面,如日志记录,是否确实起作用?您还可以在项目属性中检查是否未禁用PostSharp,以及csproj文件中是否存在PostSharp.targets导入。PostSharp还应在成功执行时在构建日志中输出信息。是的,日志方面正在工作。实际上,您似乎是对的,因为当我在模型中的一个方法上添加这个属性PermissionBasedAttribute时,它被正常命中。但是我仍然不知道为什么在can execute案例中会忽略它,因为它在小型应用程序中的工作环境与此相同。@AlexD:您对为什么在这个案例中没有找到目标有什么建议吗?我的意思是,我已经添加了编译时验证,以始终返回true,但仍然可以执行根本没有命中?
[PermissionBasedAttribute("Permission1") ]
public bool CanShowView()
{
return true;
}