.NET Core与Angular 5增删接口接收参数为null问题求助
问题分析与解决方案
1. 删除接口(del方法)的问题
你的后端用[FromBody] string p1接收参数,但Angular直接传递字符串值时,ASP.NET Core的模型绑定无法正确解析。因为当Content-Type: application/json时,JSON格式的字符串必须被双引号包裹,而直接传e.data.p1 as string会发送不带引号的纯文本,导致模型绑定失败,p1始终为null,所以返回"null"。
修正方案:
Angular端修改(二选一):
// 方案1:用对象包裹参数(更推荐,后续扩展更灵活) this.http.post('api/data/del', { p1: e.data.p1 }, { responseType: 'json', headers: new HttpHeaders({ "Content-Type": "application/json" }) }).subscribe(data => console.log(data)); // 方案2:手动给字符串加双引号,发送合法的JSON字符串 this.http.post('api/data/del', `"${e.data.p1}"`, { responseType: 'json', headers: new HttpHeaders({ "Content-Type": "application/json" }) }).subscribe(data => console.log(data));
后端对应修改(配合方案1):
推荐定义一个DTO类来接收参数,比直接用string更规范:
// 先定义一个接收请求的DTO类 public class DeleteRequest { public string P1 { get; set; } } [HttpPost] public IActionResult del([FromBody] DeleteRequest request) { try { if (request?.P1 != null) { RaschetDoppokazR1 obj = db.RaschetDoppokazR1.FirstOrDefault(x => x.P1 == request.P1); if (obj != null) { db.RaschetDoppokazR1.Remove(obj); db.SaveChanges(); return Json("OK"); } else return Json("doesnt exist"); } else return Json("null"); } catch (Exception ex) { Console.WriteLine(ex); return Json("Exception"); } }
如果坚持用[FromBody] string p1,直接用Angular的方案2即可。
2. 新增接口(add_RaschetDoppokazR1方法)的问题
你在Angular里用了JSON.stringify()把数组转成字符串,但ASP.NET Core的[FromBody] RaschetDoppokazR1[] obj期望接收的是JSON数组对象,而不是字符串。手动stringify之后,后端接收到的是字符串类型,无法转换成RaschetDoppokazR1[],所以obj为null,返回"null"。
修正方案:
Angular端直接传递数组对象,HttpClient会自动帮你序列化为JSON,不需要手动stringify:
this.http.post('api/data/add_RaschetDoppokazR1', this.tabl1.filter(x => x.id == null) as RaschetDoppokazR1[], { headers: new HttpHeaders({ "Content-Type": "application/json" }) } ).subscribe(data => console.log(data));
后端代码保持原样即可,ASP.NET Core会自动解析JSON数组为对应的对象数组。
额外小建议
- 尽量用DTO类接收前端参数,比直接用string或dynamic更安全,也便于后续维护扩展。
- 可以在后端方法里加日志打印接收到的参数,比如
Console.WriteLine($"Received request: {JsonSerializer.Serialize(request)}");,方便快速排查模型绑定问题。
内容的提问来源于stack exchange,提问作者St.S
相关产品推荐
相关产品推荐

