1
我的WebApi抛出一个内部服务器异常,并在客户端中,我试图反序列化返回异常的结果。从JSON字符串反序列化异常
控制器的操作一样:
try
{
//Do something...
}
catch (Exception ex)
{
return InternalServerError(ex);
}
并在客户端我做:
var content = response.Content.ReadAsStringAsync().Result;
var exception = JsonConvert.DeserializeObject<Exception>(content);
但会抛出异常:
会员 '类名' 不找到。
检查与Json2csharp的背景下,我得到了以下对象:
public class InnerException
{
public string Message { get; set; }
public string ExceptionMessage { get; set; }
public string ExceptionType { get; set; }
public string StackTrace { get; set; }
}
public class RootObject
{
public string Message { get; set; }
public string ExceptionMessage { get; set; }
public string ExceptionType { get; set; }
public string StackTrace { get; set; }
public InnerException InnerException { get; set; }
}
那么,是ClassName
来自哪里,什么是反序列化异常的最好方法?
EDIT
要序列我创建从Exception
衍生的新的类,并添加以下代码除外:
protected RequestException(SerializationInfo info, StreamingContext context)
{
}
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
然而,原始异常的详细信息,特别是内部异常,是丢失。
看起来是序列化的例外是派生类型,因此它比类型异常更多的属性,为此它不能被反序列化这样 - 你必须到解串器提供反序列化异常的确切类型 –
我不知道C#,但通常你不会返回一个原始的服务器端异常到前端 - 因为你正在捕获它,为什么不返回更友好的用户界面,而不会暴露你的类名和服务器端堆栈跟踪? – pherris
你可以发布你的JSON字符串吗? – Mainak