Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core 如何反序列化ASP.NET Core 2.2中的问题详细信息_Asp.net Core - Fatal编程技术网

Asp.net core 如何反序列化ASP.NET Core 2.2中的问题详细信息

Asp.net core 如何反序列化ASP.NET Core 2.2中的问题详细信息,asp.net-core,Asp.net Core,我有一个C#客户端应用程序,它调用ASP.NET核心REST服务。如果服务器上的REST服务失败,则会将其配置为根据返回“问题详细信息”json响应,例如: 在客户端应用程序中,我希望将此json消息反序列化为的实例,以方便访问详细信息。例如: ProblemDetails details = await httpResp.Content.ReadAsAsync<ProblemDetails>(); ProblemDetails=wait-httpResp.Content.Read

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

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

ProblemDetails details = await httpResp.Content.ReadAsAsync<ProblemDetails>();
ProblemDetails=wait-httpResp.Content.ReadAsAsync();
但是,反序列化引发以下异常:

System.Net.Http.UnsupportedMediaTypeException:无MediaTypeFormatter 可从内容中读取“ProblemDetails”类型的对象 媒体类型为“应用程序/问题+json”

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

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

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

您可以定义一个将从
JsonMediaTypeFormatter
继承的
ProblemDetailsMediaTypeFormatter

公共类问题详细信息MediaTypeFormatter:JsonMediaTypeFormatter
{
公共问题详细信息MediaTypeFormatter()
{
添加(新的MediaTypeHeaderValue(“应用程序/问题+json”);
}
}
用法:

var problemDetails=wait response.Content
.ReadAsAsync(新[]{new ProblemDetailsMediaTypeFormatter()},cancellationToken);

答案很好,但这有一个编译时错误。应该是(new[]{new problemdetailsmeditypeformatter()}@k29谢谢,我编辑了答案
string json = await httpResp.Content.ReadAsStringAsync();
ProblemDetails details = JsonConvert.DeserializeObject<ProblemDetails>(json);