c# - 通过lambda表达式引发异常时如何在asp.net web api中全局处理异常

标签 c# asp.net asp.net-web-api lambda

我的 web api 项目中有一个全局异常处理程序。这工作正常,除非通过 lambda 表达式引发异常。 我在下面提供了示例代码:

[HttpGet]
public IHttpActionResult Test()
{
    //Throw new Exception();// this exception is handled by my ExceptionHandler
    var list = new List<int>();
    list.Add(1);
    IEnumerable<int> result = list.Select(a => GetData(a));
    return Ok(result);
}

private static int GetData(int a)
{
    throw new Exception();//This is not handled by my global exception handler
}

这是我的全局异常处理程序

public class ExceptionHandlerAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        //Do something
    }
}

我在我的 WebApiConfig 类中注册它

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { action = "Get", id = RouteParameter.Optional }
        );
        config.Filters.Add(new ExceptionHandlerAttribute());
    }
}

最佳答案

ExceptionFilterAttribute 仅适用于在您的操作方法中 抛出的异常,请参阅 Exception Handling in ASP.NET Web API - Exception Filters .您的代码将在结果具体化期间抛出异常,从而导致 SerializationException

Global Error Handling in ASP.NET Web API 2 中所述:

Some unhandled exceptions can be processed via exception filters, but there are a number of cases that exception filters can’t handle. For example:

  • Exceptions thrown from controller constructors.
  • Exceptions thrown from message handlers.
  • Exceptions thrown during routing.
  • Exceptions thrown during response content serialization.

注册异常处理程序或记录器并采取适当的行动:

We provide two new user-replaceable services, IExceptionLogger and IExceptionHandler, to log and handle unhandled exceptions. The services are very similar, with two main differences: We support registering multiple exception loggers but only a single exception handler.

  1. Exception loggers always get called, even if we’re about to abort the connection.
  2. Exception handlers only get called when we’re still able to choose which response message to send.

参见 this answer in How do I log ALL exceptions globally for a C# MVC4 WebAPI app?两者的实现。

当然你也可以在你的 Controller 中实现可枚举,导致异常被抛出并由异常过滤器处理:

var result = list.Select(a => GetData(a)).ToList();

关于c# - 通过lambda表达式引发异常时如何在asp.net web api中全局处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28828419/

相关文章:

c# - 如何将 msmq 消息移动到子队列

c# - 我应该在哪里创建我的开发博客?

c# - 传递嵌套复杂类型的 REST URL 语法是什么?

c# - 在 Web Api 项目中读取 CollectionJson 内容

c# - 试图用类名填充文本框

c# - 关闭 WebResponse,还是保持打开状态?

asp.net - 如何为asp.net core替换machinekey?

c# - 无法删除该对象,因为在 ObjectStateManager 中找不到它

c# - 为什么我的 ASP.NET Web API ActionFilterAttribute OnActionExecuting 没有触发?

c# - 将 RGB8 byte[] 转换为 Bitmap