Web API 2.2中的全局异常处理程序没有捕获异常 [英] Global Exception Handler in Web API 2.2 is not catching an exception

查看:306
本文介绍了Web API 2.2中的全局异常处理程序没有捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.Net 4.5中有一个WebForms网站项目,我添加了ASP.Net Web API 2.2 NuGet软件包。
Web API方法被成功调用并返回预期值。



但是,在为Web API 2.2创建了一个全局异常处理程序类之后,控制器类名从ProductController到Product强制出现以下错误,则此错误未被全局异常处理程序捕获。



当从ProductController的Web API类中删除控制器后缀时出现错误消息

  {Message:没有找到匹配请求URI的HTTP资源http:// localhost / mysite / Vendors / api / 
Product / SaveProductName'。, MessageDetail:没有找到匹配名为Product的控制器的类型。

我的问题:为什么全局异常处理程序没有捕获此错误,但是当Web API方法成功发现时捕获Web API方法中引发的异常,即ProductController类名称不会更改为故意导致异常? p>

全球异常处理程序如下

  public GlobalExceptionLogger类:ExceptionLogger 
{
public GlobalExceptionLogger()
{

}

public override void Log(ExceptionLoggerContext context)
{
if(context! = null&& context.Exception!= null)
{
MyLogging.Log(context.Exception);
}
base.Log(context);
}
}

Web API控制器类(错误未被抓住通过全局异常处理程序我将类名改为Product)

  public class ProductController:ApiController 
{
//方法省略SAVE SPACE
}


解决方案

它没有被捕获,因为web api抓住这个并将其转换成404响应。框架本身处理这种情况,而不是用户代码。


I have a WebForms website project in .Net 4.5 to which I have added ASP.Net Web API 2.2 NuGet package. The Web API methods are being called successfully and returning expected values.

However, after I created a global exception handler class for Web API 2.2, and changed the controller class name from ProductController to Product to force the following error, then this error was not getting caught by global exception handler.

Error Message when controller suffix is removed from Web API class of ProductController

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/mysite/Vendors/api/
 Product/SaveProductName'.","MessageDetail":"No type was found that matches the controller named 'Product'."}

My question: Why is global exception handler not catching this error, but catching exceptions thrown in the Web API method when the Web API method is found successfully i.e. ProductController class name is not changed to deliberately cause an exception?

Global Exception Handler as below

public class GlobalExceptionLogger : ExceptionLogger
{
 public GlobalExceptionLogger()
  {

  }

public override void Log(ExceptionLoggerContext context)
 {
    if (context != null && context.Exception != null)
    { 
          MyLogging.Log( context.Exception );
    }
    base.Log(context);
 }
}

Web API controller class (for the error not being caught by global exception handler I changed the class name to Product)

 public class ProductController: ApiController
{
    //Methods omitted to SAVE SPACE
}

解决方案

It's not caught, because web api catch this and transforms it into an 404 response. The Framework itself handles this case, not the user code.

这篇关于Web API 2.2中的全局异常处理程序没有捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆