如何将异常序列化为Json

时间:2016-02-12 08:44:31

标签: c# json exception serialization

C#异常是ISerialisable因此它们也可以是DataContracts所以我不能使用JsonDataContractSerializer。

序列化JSON例外的替代方法是什么?

1 个答案:

答案 0 :(得分:3)

由于尚未真正解决此问题:只需创建一个包含所需错误属性的 Dictionary ,请使用JSON.NET对其进行序列化并将其放入 HttpResponseMessage 中:

catch (Exception e)
{
    var error = new Dictionary<string, string>
    {
        {"Type", e.GetType().ToString()},
        {"Message", e.Message},
        {"StackTrace", e.StackTrace}
    };

    foreach (DictionaryEntry data in e.Data)
        error.Add(data.Key.ToString(), data.Value.ToString());

    string json = JsonConvert.SerializeObject(error, Formatting.Indented);

    HttpResponseMessage response = new HttpResponseMessage();
    response.Content = new StringContent(json);

    return response;
}

我希望这可以帮助一些人。