【问题标题】:Using Custom IHttpActionInvoker in WebAPI for Exception Handling在 WebAPI 中使用自定义 IHttpActionInvoker 进行异常处理
【发布时间】:2013-06-27 21:39:15
【问题描述】:

我正在尝试将自定义 IHttpActionInvoker 添加到我的 WebAPI 应用程序,以防止在我的操作方法中需要大量重复的异常处理代码。

除了this article 之外,似乎没有太多关于如何做到这一点的信息。根据文章编写我的 IHttpActionInvoker 后,我添加了以下代码:

GlobalConfiguration.Configuration.Services.Remove(typeof(IHttpActionInvoker),
GlobalConfiguration.Configuration.Services.GetActionInvoker());

GlobalConfiguration.Configuration.Services.Add(typeof(IHttpActionInvoker),
new MyApiControllerActionInvoker());

进入我的 Global.asax 文件中的一个方法。现在,在执行对我的 API 的调用时,我在 Remove() 方法中得到以下异常:

The service type IHttpActionInvoker is not supported

我想我有两个问题。

  1. 考虑到关于编写自定义 IHttpActionInvoker 类的情况并不多见,这是否被认为是解决 WebAPI 应用程序中异常处理的好方法?

  2. 有谁知道为什么我在执行Remove() 方法时会得到这样的异常以及如何最好地解决这个特定问题?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api


    【解决方案1】:

    我在尝试删除服务时遇到了与您描述的相同的错误。

    我发现我不需要从全局配置中删除任何内容,因为如果您已经在容器中注册了接口,那么它会首先解决这个问题。

    例如,我正在使用 SimpleInjector,在我的 global.asax 中有这个:

    container.Register<IHttpActionInvoker , MyApiControllerActionInvoker >();
    // Register the dependency resolver.
    GlobalConfiguration.Configuration.DependencyResolver =
       new SimpleInjectorWebApiDependencyResolver(container);
    

    在运行时,它会在需要时解析 MyApiControllerActionInvoker 依赖项。

    然后您可以在您的客户 ActionInvoker 中执行异常处理,并且您的构造函数中设置的任何依赖项都将正确连接。我查看 ActionInvoker 的原因是为了获得构造函数注入,因为注入 Attributes 似乎需要属性注入。

    除了删除/插入之外,替换似乎也有效。 (在 Global.asax 中)

    GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpActionInvoker), new MyApiControllerActionInvoker(fooService));
    

    【讨论】:

      【解决方案2】:

      您是否考虑过注册一个异常过滤器?以下是一些相关文档:

      http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

      如果您只想以特定方式处理一些异常,则不必陷入动作调用层。

      【讨论】:

      • 开发人员想要捕获的许多异常都通过 Web API 转换为 HttpResponseException。此异常在调用异常过滤器之前很久就被吞没了,因此全局异常过滤器不会捕获所有内容。
      【解决方案3】:

      对我来说,它适用于 IActionInvoker 而不是 IHttpActionInvoker。据我了解,IHttpActionInvoker 用于异步 api 调用,不是吗?

      public class RepControllerActionInvoker : ControllerActionInvoker
      {
          ILogger _log;
      
          public RepControllerActionInvoker()
              : base()
          {
              _log = DependencyResolver.Current.GetService<ILogger>();
          }
      
          public override bool InvokeAction(ControllerContext controllerContext, string actionName)
          {
              try
              {
                  return base.InvokeAction(controllerContext, actionName);
              }
              catch (Exception e)
              {
                  _log.Error(e);
                  throw new HttpException(500, "Internal error");
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 2011-06-11
        • 2015-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多