如何在 ASP.NET Core 2.2 中反序列化 ProblemDetails

red*_*alx 7 asp.net-core

我有一个调用 ASP.NET Core REST 服务的 C# 客户端应用程序。如果服务器上的 REST 服务失败,则它被配置为根据rfc7807返回“问题详细信息”json 响应,例如:

{
    "type": "ServiceFault",
    "title": "A service level error occurred executing the action FooController.Create
    "status": 500,
    "detail": "Code=ServiceFault; Reference=5a0912a2-df17-4f27-8e5a-0d4828022306; Message=An error occurred creating a record.",
    "instance": "urn:foo-corp:error:5a0912a2-df17-4f27-8e5a-0d4828022306"
}
Run Code Online (Sandbox Code Playgroud)

在客户端应用程序中,我想将此 json 消息反序列化为ProblemDetails的实例,作为访问详细信息的便捷方式。例如:

ProblemDetails details = await httpResp.Content.ReadAsAsync<ProblemDetails>();
Run Code Online (Sandbox Code Playgroud)

但是,反序列化会抛出以下异常:

System.Net.Http.UnsupportedMediaTypeException:没有 MediaTypeFormatter 可用于从媒体类型为“application/problem+json”的内容中读取类型为“ProblemDetails”的对象。

Nko*_*osi 4

ReadAsAsync<T>不熟悉application/problem+json媒体类型,并且没有默认可以处理该类型的格式化程序,因此会出现错误

您可以使用长方法并先获取字符串,然后使用 Json.Net

string json = await httpResp.Content.ReadAsStringAsync();
ProblemDetails details = JsonConvert.DeserializeObject<ProblemDetails>(json);
Run Code Online (Sandbox Code Playgroud)