首页 > 解决方案 > 需要帮助解决 400 错误请求

问题描述

我试图将给定数据获取到服务器中的 POST 方法 getNumbers,它有一个参数 id,它只是返回 id 用于调试目的。所以在客户端我做如下:

 documentClickHandler=(number)=> {
    const requestOptions = {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ id: number })
    };
    fetch("http://localhost:5000/api/Documents/GetNumber", requestOptions)
        .then(response => response.json())
        .then(result => console.log(result))
        .catch(error => { console.log('request failed', error); });
  }

Which only has the purpuse to give the id to the getNumber method in the server:


[HttpPost("GetNumber")]
public string GetNumber([FromBody] string id)
       return id;
} 

This gives me an error (400 bad request) and I dont know how to solve it. Any ideas? Im in desperate need of help.

标签: c#asp.netasp.net-mvcasp.net-core.net-core

解决方案


从您的代码中删除单词“数字”。这是一个保留字

试试这个代码:

 documentClickHandler=(documentId)=> {

   var id="123"; // try this value at first, after this use your value

    const requestOptions = {
      method: 'POST',
  
      body: {id: id}
    };
    fetch("http://localhost:5000/api/Documents/GetNumber", requestOptions)
        .then(response => response.json())
        .then(result => console.log(result))
        .catch(error => { console.log('request failed', error); });
  }

和行动

[Route("~/api/Documents/GetNumber")]
public string GetNumber( string id)
       return id;
} 

推荐阅读