我正在从 flutter 向 localhost api 发送一个 post 请求。然而,服务器端的主体始终为空/空。然而,如果我向 postman 发送完全相同的请求,一切都会正常。
String json = jsonEncode(toCheck);
Map<String,String> headers = {
"Accept": "application/json",
"content-type": "application/json",
};
var response = await http.post(
Uri.parse(userPath + 'validateUser/'),
headers: headers,
body: "{\"email\":\"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="690d081f000d2901061d04080005470a0604" rel="noreferrer noopener nofollow">[email protected]</a>\",\"username\":\"\",\"mobile_phone_number\":\"\",\"password\":\"david\"}");
print(response.statusCode);
if(response.statusCode == HttpStatus.ok){
return response.body as bool;
}
print(response.body.toString());
return false;
状态代码始终为 500,并出现以下错误:
{"Message":"An error has occurred.","ExceptionMessage":"The value cannot be null"...
出现此错误是因为参数“json”为空:
[HttpPost]
[Route("validateUser/", Name = "validadeUser")]
public async Task<IHttpActionResult> ValidateUser([FromBody] string json)
{
//get the username and password to validate the user
UserClient client = JsonConvert.DeserializeObject<UserClient>(json); //error happens here because the string json is null
//...
}
Android 模拟器应用程序上的主机如下: <强> https://10.0.2.2:44304/api/user/validateUser/
PS:看起来像 Flutter POST request body is empty on server side 的重复项和 Flutter Dart HTTP POST request body is empty on server side但这些解决方案都不适合我,因此我发布了一个新问题。
最佳答案
我花了一段时间才发现错误......但最终我发现了!
您的 API 从请求正文中获取字符串参数:
ValidateUser([FromBody] string json)
乍一看似乎没问题,因为实际上,您正在发送一个 json 字符串作为请求正文。但问题是,因为您还使用这些 header :
{
"Accept": "application/json",
"content-type": "application/json",
}
此位:"content-type": "application/json"
会将您格式正确的 json 字符串转换为实际的 json 对象!因此,当它到达您的 API 时,它将不再是字符串,因此您的 API 将无法正确接收它。
解决方案是从 header 中删除 "content-type": "application/json"
并保持请求正文和 API 函数不变,或者更改 API至:
ValidateUser([FromBody] object json)
后者可能是最方便的,因为无论如何你都要把它从 json 字符串解析为 json 对象! 🙂
(使用此 API 函数,您还可以从 header 中删除 "content-type": "application/json"
位,然后发送请求正文,如下所示:
body: jsonDecode("{\"email\":\"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a0e0b1c030e2a02051e070b030644090507" rel="noreferrer noopener nofollow">[email protected]</a>\",\"username\":\"\",\"mobile_phone_number\":\"\",\"password\":\"david\"}"),
或者一开始就不对其进行 jsonEncode...只需将其作为对象发送即可。这与将其作为 header 中带有 "content-type": "application/json"
的 json 字符串发送具有相同的效果。)
顺便说一句,作为一般规则,请确保在开发代码时在代码中添加大量打印和日志语句!它将帮助您发现整个过程中任何不符合您预期的情况。 😉(我就是这样发现的。)
关于json - Flutter POST json 请求正文在服务器端为空/null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73557840/