2013-02-21 26 views
1

趕上他們,我有2個屬性:拋出一個自定義異常,並與Postsharp

  1. SecuredOperationAttribute
  2. ExceptionPolicyAttribute

如果用戶不具有對控制器的操作的訪問,然後我扔自定義NonAuthorizedException但我不能趕上ExceptionPolicyAttribute

我的代碼:

[LogMethod] 
[ExceptionPolicy] 
public ActionResult Edit(int id) 
{ 
    // some works on here 
} 

[Serializable] 
public class ExceptionPolicyAttribute : OnExceptionAspect 
{ 
    private ILog logger; 
    private string methodName; 

    public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo) 
    { 
     this.methodName = method.DeclaringType.FullName + "." + method.Name; 
    } 

    public override void OnException(MethodExecutionArgs args) 
    { 
     Guid guid = Guid.NewGuid(); 

     var stringBuilder = new StringBuilder(1024); 

     // Write the exit message. 
     stringBuilder.Append(this.methodName); 
     stringBuilder.Append('('); 

     // Write the current instance object, unless the method 
     // is static. 
     object instance = args.Instance; 
     if (instance != null) 
     { 
      stringBuilder.Append("this="); 
      stringBuilder.Append(instance); 
      if (args.Arguments.Count > 0) 
       stringBuilder.Append("; "); 
     } 

     // Write the list of all arguments. 
     for (int i = 0; i < args.Arguments.Count; i++) 
     { 
      if (i > 0) 
       stringBuilder.Append(", "); 
      stringBuilder.Append(args.Arguments.GetArgument(i) ?? "null"); 
     } 

     // Write the exception message. 
     stringBuilder.AppendFormat("): Exception "); 
     stringBuilder.Append(args.Exception.GetType().Name); 
     stringBuilder.Append(": "); 
     stringBuilder.Append(args.Exception.Message); 

     logger.Error(stringBuilder.ToString(), args.Exception); 

     args.FlowBehavior = FlowBehavior.Continue; 
    } 

    public override Type GetExceptionType(System.Reflection.MethodBase targetMethod) 
    { 
     return typeof(NonAuthorizedException); 
    } 
} 

和安全屬性是:

[Serializable] 
public class SecuredOperationAttribute: OnMethodBoundaryAspect 
{ 
    public override void OnEntry(MethodExecutionArgs args) 
    { 
     IUserManager userManager = new UserManager(); 
     int userId = userManager.GetUserIdFromCookie; 
     AdminUser adminUser = GenericSessionHelper<AdminUser>.Get(userId.ToString(), State.Session); 
     if(!User.CanAccess) 
     { 
      args.ReturnValue = null; 
      throw new NonAuthorizedException(string.Format("{0} userId li kullanıcının {1} işlemini yapmak için yetkisi yoktur",userId,args.Method.Name)); 
     } 
     return; 
    } 
} 

可能是什麼問題?我是否以錯誤的方式使用postsharp?

回答

1

我找到了解決辦法: 我使用的屬性,如:

[SecuredOperation] 
[ExceptionPolicy] 
public ActionResult Edit(int id) 

但ExceptionPolicy無法趕上例外。所以我把ExceptionPolicy移到了控制器類的頂端:

[ExceptionPolicy] 
    public class UserController : BaseAuthorizedUserController 

現在它工作。