2

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

  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();
        }
    }
4

2 回答 2

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;
    }
于 2019-07-31T05:36:55.470 回答
-1

创建自定义异常并将所需的任何其他数据放入其属性中。然后,您在异常过滤器中的一个 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");
于 2016-05-12T06:29:27.393 回答