C# 使用HttpClient.PostAsync时,如何从BadRequest响应捕获消息
我有一些代码可以通过HttpClient.PostAsync调用API 根据我发送的内容,API可能会响应HTTP 400/Bad请求消息 在本例中,我控制服务器端代码,因此我知道它返回有关调用失败原因的详细信息。然而,在对客户的回复中,这个细节似乎丢失了 是否可以从客户端捕获BadRequestObjectResult.Value 如果没有,什么是回退错误消息的正确方法 下面的代码是按执行顺序排列的,带有注释(希望)可以清楚地说明发生了什么C# 使用HttpClient.PostAsync时,如何从BadRequest响应捕获消息,c#,asp.net-mvc,api,http,C#,Asp.net Mvc,Api,Http,我有一些代码可以通过HttpClient.PostAsync调用API 根据我发送的内容,API可能会响应HTTP 400/Bad请求消息 在本例中,我控制服务器端代码,因此我知道它返回有关调用失败原因的详细信息。然而,在对客户的回复中,这个细节似乎丢失了 是否可以从客户端捕获BadRequestObjectResult.Value 如果没有,什么是回退错误消息的正确方法 下面的代码是按执行顺序排列的,带有注释(希望)可以清楚地说明发生了什么 =-=-=-=-=-=-=-=-=-=STARTIN
=-=-=-=-=-=-=-=-=-=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.
}
我想你想要
。。。else{var error=await response.Content.ReadAsStringAsync();}
尽管您可能需要类而不是json字符串