React调用ASP.NET Core POST接口传参失败的原因与解决方法
问题分析与解决:POST请求参数无法绑定的问题
问题场景
服务端(C# .NET Core 3.1)代码:
[EnableCors("CorsApi")] [Route("[action]", Name = "DeleteFile")] [HttpPost] public List<string> DeleteFile(string pathFile) { string commandDelete = "rm " + pathFile; List<string> results = ExecuteCommand(commandDelete, true); return results; }
客户端(React)请求代码:
(async () => { const response = await fetch('https://localhost:7198/api/Proj/DeleteFile', { method: 'POST', body: JSON.stringify({ pathFile: srcFile, }), headers: { 'Content-type': 'application/json; charset=UTF-8' }, }) const data = await response.json() console.log(data) })()
问题:上述POST请求无法正常工作,仅当将参数放在URL查询字符串中时才能运行。
原因分析
在.NET Core的模型绑定规则中,简单类型(如string、int等)默认会从URL查询字符串、表单数据或路由值中绑定,不会自动从请求Body的JSON中读取。你的客户端将参数放在JSON格式的请求Body里,但服务端的pathFile参数未指定绑定来源,框架无法从Body中获取该值,导致参数为null,进而请求失败。
解决方案
有两种常用的解决方式:
方式1:给参数添加[FromBody]特性
明确告诉框架从请求Body中绑定该参数,修改服务端代码:
[EnableCors("CorsApi")] [Route("[action]", Name = "DeleteFile")] [HttpPost] public List<string> DeleteFile([FromBody] string pathFile) { string commandDelete = "rm " + pathFile; List<string> results = ExecuteCommand(commandDelete, true); return results; }
此时需同步调整客户端请求Body,直接传递字符串而非对象:
body: JSON.stringify(srcFile),
方式2:封装参数为实体类(推荐,扩展性更强)
先定义参数实体类:
public class DeleteFileRequest { public string pathFile { get; set; } }
再修改控制器方法:
[EnableCors("CorsApi")] [Route("[action]", Name = "DeleteFile")] [HttpPost] public List<string> DeleteFile([FromBody] DeleteFileRequest request) { string commandDelete = "rm " + request.pathFile; List<string> results = ExecuteCommand(commandDelete, true); return results; }
这种方式下,客户端的请求代码无需修改,保持原JSON对象格式即可。
内容的提问来源于stack exchange,提问作者prog_prog
相关产品推荐
相关产品推荐

