无法处理从.NET 7.0 Controller发起的Axios POST请求
问题:Axios发送POST请求到.NET 7 Controller返回400 Bad Request
问题描述
前端通过Axios发送POST请求,后端.NET 7的Controller能正常响应GET请求,但POST请求返回400错误。
前端Axios代码
const httpLink = 'https://www.myServer.com' + '/api/DBCom/saveInformation'; var postAxios = axios({ method: 'post', url: httpLink, params: {tableName: tableName}, headers: {'Content-Type': 'application/json' }, data: rowInfo }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); alert('Error' + error.response.data); answer = false; });
后端.NET 7 Controller代码
[Route("api/[Controller]")] [ApiController] public class DBComController : ControllerBase { [HttpGet("Index")] public string Index() { return "hello all"; } [HttpPost("saveInformation")] public string saveInformation([FromBody] string value) { Console.WriteLine(value); return "hello from post"; } }
错误信息
POST https: ############/api/DBCom/saveInformation 400 (Bad Request) dispatchXhrRequest @ xhr.js:256 xhr @ xhr.js:49 dispatchRequest @ dispatchRequest.js:51 request @ Axios.js:146 wrap @ bind.js:5 User.onBlurOfTextbox @ User.js:265 onBlur @ User.js:371 callCallback @ react-dom.development.js:4164 invokeGuardedCallbackDev @ react-dom.development.js:4213 invokeGuardedCallback @ react-dom.development.js:4277 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291 executeDispatch @ react-dom.development.js:9041 processDispatchQueueItemsInOrder @ react-dom.development.js:9073 processDispatchQueue @ react-dom.development.js:9086 dispatchEventsForPlugins @ react-dom.development.js:9097 (anonymous) @ react-dom.development.js:9288 batchedUpdates$1 @ react-dom.development.js:26140 batchedUpdates @ react-dom.development.js:3991 dispatchEventForPluginEventSystem @ react-dom.development.js:9287 dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465 dispatchEvent @ react-dom.development.js:6457 dispatchDiscreteEvent @ react-dom.development.js:6430 Show 20 more frames Show less User.js:278 AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
解决方法
核心原因
后端用[FromBody] string value接收请求体时,.NET默认期望的是JSON格式的字符串(即被双引号包裹的字符串,比如"some data"),但你的Axios请求中data: rowInfo如果是一个对象,Axios会把它序列化成JSON对象(比如{key: value}),这和后端期望的字符串格式不匹配,导致模型绑定失败,返回400错误。
方案1:后端改为接收实体类(推荐)
如果rowInfo是一个结构化对象,定义对应的实体类来接收,这是REST API的标准做法:
// 定义与rowInfo结构匹配的实体类 public class RowInfo { // 根据实际需求添加属性,示例: public string Username { get; set; } public int Age { get; set; } // 其他属性... } // 修改Controller方法 [HttpPost("saveInformation")] public string saveInformation([FromBody] RowInfo value) { Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(value)); return "hello from post"; }
前端代码无需修改,Axios会自动把rowInfo对象序列化成JSON对象,后端能正常绑定。
方案2:前端传递JSON字符串,后端保持接收string
如果确实需要后端接收字符串,前端需要把rowInfo序列化为JSON字符串:
var postAxios = axios({ method: 'post', url: httpLink, params: {tableName: tableName}, headers: {'Content-Type': 'application/json' }, data: JSON.stringify(rowInfo) // 将对象转为JSON格式字符串 })
方案3:后端直接读取原始请求体
如果不想修改前端,也可以绕过模型绑定,直接读取请求体原始内容:
[HttpPost("saveInformation")] public async Task<string> saveInformation() { using var reader = new StreamReader(Request.Body); var value = await reader.ReadToEndAsync(); Console.WriteLine(value); return "hello from post"; }
额外注意点
- 确认
rowInfo不是undefined或null,空请求体也会导致400错误。 - 当前
params: {tableName: tableName}会将参数拼在URL查询字符串中,如果需要将其放入请求体,需调整到data对象内。
内容的提问来源于stack exchange,提问作者Jose Cabrera Zuniga
相关产品推荐
相关产品推荐

