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

7
我有一个C#客户端应用程序,调用ASP.NET Core REST服务。如果服务器上的REST服务失败,则配置为返回“问题详细信息”JSON响应,格式遵循rfc7807,例如:
{
    "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"
}

在客户端应用程序中,我想将此JSON消息反序列化为ProblemDetails的实例,作为访问详细信息的便捷方式。例如:
ProblemDetails details = await httpResp.Content.ReadAsAsync<ProblemDetails>();

然而,反序列化会抛出以下异常:

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

2个回答

4
你可以定义一个 ProblemDetailsMediaTypeFormatter,它将继承自JsonMediaTypeFormatter
    public class ProblemDetailsMediaTypeFormatter : JsonMediaTypeFormatter
    {
        public ProblemDetailsMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/problem+json"));
        }
    }

用法:

var problemDetails = await response.Content
    .ReadAsAsync<ProblemDetails>(new [] { new ProblemDetailsMediaTypeFormatter() }, cancellationToken);

1
很棒的答案,但是编译时会有错误。 应该是(new [] { new ProblemDetailsMediaTypeFormatter() } - k29

4

ReadAsAsync<T> 无法处理 application/problem+json 媒体类型,并且默认情况下没有格式化程序可以处理该类型,因此出现错误。

您可以采用长方式,首先获取字符串,然后使用 Json.Net。

string json = await httpResp.Content.ReadAsStringAsync();
ProblemDetails details = JsonConvert.DeserializeObject<ProblemDetails>(json);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接