Fetch, controller FromBody 错误

Fetch, controller FromBody wrong

我正在抓取以更改我的记录,值 newInsert 在抓取中为真,但在控制器中为假。

获取:

fetch('api/Test/UpdateOrInsertType', {
            headers: { 'Content-Type': 'application/json' },
            method: 'POST',
            body: JSON.stringify({
                'newInsert': newInsert  //Console.log -> true
            })

控制器:

[HttpPost("UpdateOrInsertType")]
        public IActionResult UpdateOrInsertType([FromBody] bool newInsert) 
// Debugger newInsert -> false
        {
            try
            {
                return Ok(Test.UpdateOrInsertType(newInsert));
            }
            catch (Exception ex)
            {
                return Conflict(ex);
            }
        }

Json 不能与基本类型一起正常工作。如果您不想使用 json.stringify,则必须创建一个 ViewModel

public class ViewModel
{
public bool NewInsert {get; set;}
}

和行动

[HttpPost("UpdateOrInsertType")]
public IActionResult UpdateOrInsertType([FromBody] ViewModel model) 
{
bool newInsert=model.NewInsert

或者您可以删除 { 'Content-Type': 'application/json' }

   fetch('api/Test/UpdateOrInsertType', {
   method: 'POST',
  body: { newInsert: newInsert } 
        })

并删除 [FromBody]

[HttpPost("UpdateOrInsertType")]
 public IActionResult UpdateOrInsertType( bool newInsert) 

在这种情况下,您不应使用 JSON.stringify

只需将原始 javascript 对象传递给 fetch body:

fetch('api/Test/UpdateOrInsertType', {
            method: 'POST',
            body:
            {
                newInsert: newInsert
            }
        });

现在在服务器端它将被识别为 bool 属性.