获取操作局部变量名称和值OnException自定义过滤器

时间:2016-05-11 21:50:46

标签: asp.net-mvc asp.net-mvc-filters

想要将操作的变量值检索到自定义过滤器

  public class TrackError : IExceptionFilter
            {
              public void OnException(ExceptionContext filterContext)
                {
                    // How to get the value of X ?????????????????                   
                }
        }

控制器:

[TrackError]
public class HomeController : Controller
    {

        public ActionResult Index()
        {

                int x = 0;

            throw new Exception("XYZ");
            return View();
        }
    }

2 个答案:

答案 0 :(得分:0)

创建自定义异常并将所需的任何其他数据放入其属性中。然后在异常过滤器中的一个catch块中捕获该异常类型。

public class ServiceException : Exception, ISerializable
{
        public WhateverType X {get;set;}
        public string Message{get;set;}

        public ServiceException()
        {
            // Add implementation.
        }

        public ServiceException(WhateverType x, string message)
        {
            this.X = x;
            this.Message = message;
        }

        public ServiceException(string message):base(message)
        {
        }

        public ServiceException(string message, Exception inner)
        {
            // Add implementation.
        }

        // This constructor is needed for serialization.
        protected ServiceException(SerializationInfo info, StreamingContext context)
        {
            // Add implementation.
        }
}

然后在过滤器中:

public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception is ServiceException)
            {
             //Here you can access (context.Exception as ServiceException).X
            }
}

抛出你的异常,如:

throw new ServiceException(X, "Your custom message gore here");

答案 1 :(得分:0)

您尝试过这种方式吗?

int x = 0;
    try
    {


        DoSomethingThatMightFail(s);
    }
    catch (Exception ex) when (Log(ex, "An error occurred", new[]{x,s}))
    {
        // this catch block will never be reached
    }

    ...

    static bool Log(Exception ex, string message, params object[] args)
    {
        Debug.Print(message, args);
        return false;
    }