我通过 HttpResponseException 从 WebApi 返回自定义异常。例如:
//Base class for all custom app exceptions
public class MyAppException : Exception {}
//Custom exceptions
public class MyCustomException1 : MyAppException { //custom properties}
public class MyCustomException2 : MyAppException { //other custom properties}
客户端是一个 HttpClient,返回的消息看起来像这样:
{"Message":"An error has occurred.","ExceptionMessage":"Exception of type 'MyApp.Exceptions.MyCustomException1 ' was thrown.","ExceptionType":"MyApp.Exceptions.MyCustomException1 ","StackTrace":null}
这里有两个问题:
- 自定义异常的属性不在消息中
- 响应消息不能反序列化为自定义异常
有没有办法将消息反序列化为正确的异常?
最佳答案
使用Custom model binder
分析ExceptionType
属性来创建正确异常的实例。
请看看这个工作Github sample
已编辑
关于c# - 反序列化来自 Web Api 的自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26731873/