【问题标题】:ProblemDetails doesn't serialize back to a ProblemDetails objectProblemDetails 不会序列化回 ProblemDetails 对象
【发布时间】:2020-11-30 13:03:46
【问题描述】:

我有一个用 core 3.1 编写的 REST 服务。当出现错误时,我使用控制器中的 Problem() 方法返回一个 ProblemDetails 对象。当我通过 Swagger UI 运行它时,我得到了我所期望的。

{
  "isError": true,
  "responseException": {
    "exceptionMessage": {
      "type": "ApplicationException",
      "title": "Internal Server Error",
      "status": 500,
      "detail": "An Error Happened. I want this message to bubble up.",
      "instance": "/v1/TestAdapter/GetError",
      "traceId": "|31cf435b-44b49327cac802b2."
    }
  }
}

当我从服务调用中得到它时,我想将它序列化回一个问题详细信息对象。但这不起作用。我一直在寻找应该序列化的对象。

我可以这样做并获取数据。

var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

但这不起作用。 (所有字段均为空。)

var typedBody = JsonConvert.DeserializeObject<ProblemDetails>(responseText, new JsonSerializerSettings());

我应该在这里做什么才能将它编组回一个 ProblemDetails 对象?

【问题讨论】:

标签: c# json rest


【解决方案1】:

对于序列化,您至少需要:

  • 一个空的或默认的构造函数 - 你有那个,否则你会得到一个错误
  • 可设置的属性。对于 System.Text.Json 和 JSON.net 私有可设置属性将起作用。只读属性不起作用。例如
public string WontWork { get; } 

public string DoesWork { get; private set; }

【讨论】:

    【解决方案2】:

    所以问题是我自己造成的。我安装了一个包装器来改变我的返回对象。我安装它是为了测试将错误消息返回给调用者的最佳方式。在此过程中,我创建了一个客户端不知道如何处理的返回值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 2014-01-28
      • 2022-01-03
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      相关资源
      最近更新 更多