【发布时间】:2021-08-31 22:44:02
【问题描述】:
我正在尝试从 Angular 向我的 C# ASP.NET Core 2.2 后端发出发布请求。 API 被命中,但我的参数没有被 API 接收,而是被初始化为 null。
当我检查网络选项卡时,我的参数正在发送并且与函数中的参数类型匹配,但它仍然显示为空。我也尝试在参数中添加[FromBody] 属性,但这没有区别。
为什么后端收不到参数?
后端 API 结构
[HttpPost]
public void GetCanadaPostRates(ShippingRateModel info)
{
// this is being hit but info is showing as null
// do something
}
前端服务:
export class ShippingService {
private apiUrl = environment.apiBaseUrl + '_3rdPartyShipping/';
constructor(private http: HttpClient) {}
getCanadaPostShippingQuote(info) {
return this.http.post<any>(this.apiUrl + 'GetCanadaPostRates', info);
}
}
前端服务调用:
this.shippingService.getCanadaPostShippingQuote(shippingRates).subscribe(res => {})
前端模型:
export class ShippingRateModel {
WeightKg: number;
OriginPostalCode: string;
DestPostalCode: string;
}
后端模型:
namespace Server.Models
{
public class ShippingRateModel
{
float WeightKg { get; set; }
string OriginPostalCode { get; set; }
string DestPostalCode { get; set; }
}
}
网络请求截图:
【问题讨论】:
-
你应该这样称呼
post<ShippingRateModel> -
尝试在后端模型的
ShippingRateModel中公开您的属性;与问题无关的@viveknuna(有效负载具有值),但可能是一个很好的建议 -
@BrettCaswell 谢谢你的工作,如果你把它写成答案,我会把它标记为接受
标签: c# angular .net-core asp.net-core-webapi asp.net-core-2.2