如何在Web API中捕获SerializationException? [英] How do I trap a SerializationException in Web API?

查看:79
本文介绍了如何在Web API中捕获SerializationException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Web API Web服务,在某些情况下会引发SerializationException。问题是我无法在服务器端捕获和记录此异常-它显示的唯一位置是在对客户端的HTTP响应的正文中。

I have an ASP.NET Web API web service which throws a SerializationException in certain circumstances. The problem is that I'm unable to trap and log this exception server-side -- the only place it shows up is in the body of the HTTP response to the client.

我注册了 ExceptionFilterAttribute ,如 ASP.NET Web API中的异常处理,并验证了当我在控制器中引发异常时它是否可以正常工作。不幸的是,在响应过程中(在控制器之后)引发了SerializationException,并且似乎被ASP.NET完全吞噬了。我还尝试将 Application_Error()钩在Global.asax.cs中,但它也没有出现在那儿。

I registered an ExceptionFilterAttribute as described in Exception Handling in ASP.NET Web API and verified that it works properly when I throw an exception within my controller. Unfortunately the SerializationException is being thrown during the response (after the controller) and appears to be completely swallowed up by ASP.NET. I also tried hooking Application_Error() in Global.asax.cs but it didn't show up there either.

如何在Web API响应期间捕获SerializationException异常?

How can I catch SerializationException exceptions during the Web API response?

推荐答案

如果您使用 ApiController.CreateResponse()方法并返回 HttpResponseMessage ,然后可以执行 response.Content.LoadIntoBufferAsync ().Wait(),这将迫使序列化在您仍在执行操作时发生,因此可以捕获异常。

If, instead of returning an object, you use the ApiController.CreateResponse() method and return a HttpResponseMessage you can then do response.Content.LoadIntoBufferAsync().Wait() and that will force the serialization to happen whilst you are still in the action and therefore can catch the exception.

这篇关于如何在Web API中捕获SerializationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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