如何解决使用HttpClient.PostAsync时如何从BadRequest响应中捕获消息
我有一些代码可以通过HttpClient.PostAsync调用API。
根据我发送的内容,API可能会以HTTP 400 /错误请求消息作为响应。
在这种情况下,我控制服务器端代码,所以我知道它返回有关调用失败原因的详细信息。但是,这些细节似乎在回复客户时丢失了。
是否可以从客户端捕获BadRequestObjectResult.Value?
如果没有,反击错误消息的正确方法是什么?
下面的代码按执行顺序进行排列,并带有注释(希望)使发生的事情清晰可见。
=-=-=-=-=-=-=-=-=-=STARTING ON THE CLIENT SIDE,WE SEND SOME REQUEST-=-=-=-=-=-=-=-=
var response = await client.PostAsync(url,someJSONData);
=-=-=-=-=-=-=-=-=-=OVER TO THE SERVER NOW=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//this code happens on the server-side - it has received the json data and found some problem.
if(string.IsNullOrEmpty(firstname))
{
errors.Add("First name is required.");
}
//note that the "error" property will have details about the failure.
return BadRequest(new { success = false,message = "Fail",error = errors });
=-=-=-=-=-=-=-=-=-=BACK TO THE CLIENT,WHO HAS BEEN WAITING PATIENTLY=-=
if (response.IsSuccessStatusCode)
{
}
else
{
//we land here,because the status code is a 400.
//But the detail is nowhere to be found in the "response" object.
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。