C# Visual Studio 中发生 422(无法处理的实体)错误时如何读取 json 响应

Már*_*rte 1 rest json httpwebresponse visual-studio-2010 c#-4.0

我正在使用“PUT”方法将一些 JSON 数据发送到 Web 服务,但遇到422 无法处理的实体错误。
我怎样才能真正看到 JSON 格式的服务器响应?我深入研究了异常,但仍然找不到 json 响应。

前任:

JSON 请求:

{
  customer:
  {
    name: "asd",
    address: "test"
  }
}
Run Code Online (Sandbox Code Playgroud)

如果一切正常,它应该回复我一些 JSON 数据。

前任:

{
  customer:
  {
    id: 1,
    name: "asd",
    address: "test"
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以捕获 WebExpection 并从中获取 Response 并提取正确的错误消息:

代码 :

catch (WebException ex)
{
    using (var sr = new StreamReader(ex.Response.GetResponseStream()))
    {
       var data = sr.ReadToEnd();                    
       throw new ApplicationException(data);
    }                
}
Run Code Online (Sandbox Code Playgroud)