iaa*_*acp 0 c# asp.net-mvc json vue.js .net-core
我正在使用 fetch 调用 POST 控制器操作,但在控制器中,主体似乎为空。
这是我的获取代码片段 - 这是在 .net core 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));
Run Code Online (Sandbox Code Playgroud)
这是我在 Firefox 中看到的请求(和负载):
但在我的 .net core 后端中,当 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();
}
Run Code Online (Sandbox Code Playgroud)
在这里,在我的调试器中,body和requestBody均为空。有任何想法吗?
.NET 不会看到您传递字符串,它会看到 JSON,因为您传递了Content-Type的标头application/json,因此它会尝试反序列化它并将其映射到您的请求对象。在你的情况下,因为你的参数是string body解析器尝试将 JSON 对象映射到你的string并且失败 - 所以它通过了null。
您可以尝试更改要作为text/plain(content-type或删除content-type标头)传递的请求,或将您的 API 参数更改为您要发送的对象:
public IActionResult AddNewProduct([FromBody] Product newProduct)
{
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12506 次 |
| 最近记录: |