Angular向C# Core WebAPI传值,控制器接收为null如何解决?
问题:Angular向ASP.NET Core WebAPI发送PUT请求时,控制器接收的模型为null
我通过Angular向C# Core WebAPI发送表单数据,控制台已打印出完整的待发送参数,但调试WebAPI控制器时,接收的模型数据始终为null。
Angular组件调用代码
this.commonService.updatescheduleFee(this.flatfeeModel).then((response: ResponseModel) => { this.toasterMessageService.showSuccess('Fee Schedule Updated Successfully!'); });
API服务调用代码
async updatescheduleFee(params: any) { params['amount2'] = 100; console.log('FeeSchedule-params', params); return await this.ws.put(`${this.billingApiUrl}/invoice/FeeSchedule`, params).toPromise(); }
ASP.NET Core WebAPI控制器代码
[HttpPut("FeeSchedule")] public async Task<IActionResult> UpdateFeeSchedule(FeeScheduleRequest1Dto model) { try { // 调试时model为null } }
解决方法
添加[FromBody]特性
ASP.NET Core默认不会自动将PUT请求的Body绑定到复杂类型参数,必须在控制器参数上标记[FromBody]:[HttpPut("FeeSchedule")] public async Task<IActionResult> UpdateFeeSchedule([FromBody] FeeScheduleRequest1Dto model) { try { // 业务逻辑 } }匹配参数与模型的命名规则
确保前端参数名和后端模型类的属性名大小写匹配(ASP.NET Core默认遵循驼峰命名映射,比如前端amount2对应后端模型的Amount2),且模型类的属性都有公共的getter和setter:public class FeeScheduleRequest1Dto { public int Id { get; set; } public decimal Amount2 { get; set; } // 其他需绑定的属性 }调整请求格式(针对表单数据)
如果前端发送的是表单数据(非JSON),需将参数转换为FormData并设置对应Content-Type,同时控制器参数改用[FromForm]:
Angular代码修改:async updatescheduleFee(params: any) { params['amount2'] = 100; const formData = new FormData(); Object.keys(params).forEach(key => formData.append(key, params[key])); return await this.ws.put(`${this.billingApiUrl}/invoice/FeeSchedule`, formData).toPromise(); }控制器代码修改:
[HttpPut("FeeSchedule")] public async Task<IActionResult> UpdateFeeSchedule([FromForm] FeeScheduleRequest1Dto model) { try { // 业务逻辑 } }验证请求Payload
用浏览器开发者工具查看Network标签下的PUT请求,确认Payload格式正确(JSON无语法错误、表单数据键值对完整)。
内容的提问来源于stack exchange,提问作者saurav.rox
相关产品推荐
相关产品推荐

