【发布时间】:2019-11-23 17:31:51
【问题描述】:
我正在使用 fetch 调用 POST 控制器操作,但在控制器中,主体似乎为空。
这是我的获取代码 sn-p - 这是在 .net 核心 Vue 项目中。这是一个打字稿文件。
var data = JSON.stringify(this.newProduct);
console.log(data)
fetch('api/Product/AddNewProduct', {
method: 'POST',
body: data,
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
这是我在 Firefox 中看到的请求(和有效负载):
但在我的 .net 核心后端中,当 API 被命中时,我似乎无法获取请求中的正文或任何内容的值。
[HttpPost("[action]")]
public IActionResult AddNewProduct([FromBody] string body)
{
Product newProduct;
try
{
/*Added the below snippet for testing, not sure if actually necessary */
using (var reader = new StreamReader(Request.Body))
{
var requestBody = reader.ReadToEnd();
// Do something
}
//Convert the request body to an object
newProduct = JsonConvert.DeserializeObject<Product>(body);
}
catch (Exception e)
{
return new BadRequestResult();
}
这里,在我的调试器中,body 和 requestBody 都是空的。有任何想法吗?
【问题讨论】:
-
不要再读了。它已经在您的方法参数中传递。
-
我只是为了测试目的而阅读它,因为名为 body 的方法参数为空(根据我帖子的最后一行)。有什么想法吗?
标签: c# json asp.net-mvc vue.js .net-core