拋出自定義異常並使用 Postsharp 捕獲它們 (Throw an custom exception and catch them with Postsharp)


問題描述

拋出自定義異常並使用 Postsharp 捕獲它們 (Throw an custom exception and catch them with Postsharp)

I have 2 attributes:

  1. SecuredOperationAttribute 
  2. ExceptionPolicyAttribute

If user doesn't has an access to the action on controller then I throw an custom NonAuthorizedException but I can't catch it on ExceptionPolicyAttribute

My code:

[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);
    }
}

And the secure attribute is:

[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;
    }
}

What could be a problem? Am I using postsharp in a wrong way?

‑‑‑‑‑

參考解法

方法 1:

I found the solution: I was using attributes as like :

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

but ExceptionPolicy couldn't catch exception. so I moved the ExceptionPolicy to top of the Controller Class:

[ExceptionPolicy]
    public class UserController : BaseAuthorizedUserController

now it works.

(by shortcodeshortcode)

參考文件

  1. Throw an custom exception and catch them with Postsharp (CC BY‑SA 3.0/4.0)

#Security #postsharp #exception-handling #C#






相關問題

只允許 oracle db 登錄到特定的應用程序? (Allowing oracle db login only to specific application?)

在桌面應用程序中保存用戶名和密碼 (Saving username & password in desktop app)

如何使用算法 RSA/ECB/PKCS1Padding 通過 JavaScript 解密加密字符串 (How to decrypt through JavaScript of encrypted string using algorithm RSA/ECB/PKCS1Padding)

wcf:將用戶名添加到消息頭是否安全? (wcf: adding username to the message header is this secure?)

沒有 .htaccess 的安全目錄密碼保護 (Secure directory password protection without .htaccess)

無法在 Oracle 表上創建簡單視圖 (Unable to create a simple view on Oracle table)

當請求來自調度程序時,無法寫入 App_Data (Cannot write in App_Data when request is from scheduler)

安全的 PHP 文件上傳 (Secure PHP file uploading)

Grails Spring 安全配置通過 xml (Grails Spring Security Configuration thru xml)

醫療應用的安全要求 (Security Requirements for Medical Applications)

如何保護 Silverlight 應用程序 (How to Secure Silverlight Application)

在使用 azure 流量管理器和 azure 應用程序網關與 WAF 時實現國家級阻止 (Achieve country level blocking while using azure traffic manager and azure application gateway with WAF)







留言討論