asp.net-mvc - .NET Core 2 Web API:[FromBody] 嵌套对象未绑定
问题描述
我的控制器中有该发布请求:
[HttpPost("subscriptions")]
[Authorize(Policy = Policies.Admin)]
public async Task<IActionResult> PostSubscription([FromBody] PostSubscriptionBindingModel model) { ... }
哪里PostSubscriptionBindingModel
是:
public class PostSubscriptionBindingModel
{
[Required]
public DateTime StartsOn { get; set; }
[Required]
public DateTime ExpiresOn { get; set; }
[Required]
public Gym Gyms { get; set; }
[Required]
public int SubscriptionTypeId { get; set; }
[Required]
public string UserId { get; set; }
public PaymentBindingModel Payment { get; set; }
public class PaymentBindingModel
{
[Required]
public double Amount { get; internal set; }
[Required]
public PaymentType Type { get; internal set; }
[RequiredArray]
public InstalmentBindingModel[] Instalments { get; internal set; }
public class InstalmentBindingModel
{
[Required]
public double Amount { get; internal set; }
public DateTime? ExpiresOn { get; internal set; }
[Required]
public bool IsSetPaid { get; internal set; }
}
}
}
在Angular
(v.6)方面,我有一个使用这种方法的服务:
postSubscription(model: IPostSubscription): Observable<ISubscription> {
return this.http.post<ISubscription>(this.originUrl + '/api/subscriptions', model)
.catch((reason: any) => this.handleError(reason));
}
当我尝试将对象发布到 web api 控制器时,在 Angular 服务postSubscription
方法中,模型已完全初始化,在 web api 端,只有对象的第一级具有值。Payment
(嵌套类型的)属性PaymentBindingModel
不为 null,但其属性未初始化,就像它们未绑定一样。
我怎么解决这个问题?
编辑(添加图像)
编辑 2(添加客户端代码后模型)
export interface IPostSubscription {
startsOn: Date;
expiresOn: Date;
gyms: Gym;
subscriptionTypeId: number;
userId: string;
payment?: ISubscriptionPayment;
}
export interface ISubscriptionPayment {
amount: number;
type: PaymentType;
instalments: ISubscriptionPaymentInstalment[];
}
export interface ISubscriptionPaymentInstalment {
amount: number;
expiresOn?: Date;
isSetPaid: boolean;
}
非常感谢!
解决方案
为了使模型绑定正常工作,属性上的访问器get
和set
应该是默认的,它public
位于公共属性上。制作访问器private
, internal
, 或protected
将导致模型绑定失败。
大多数时候你甚至不会得到错误;属性将仅显示属性数据类型的默认值。
模型绑定器使用来自外部源的数据设置属性,因此它们需要可公开访问。
推荐阅读
- apache-spark - 一个热编码复合字段
- css - 如何在移动视图中使填充响应?
- wordpress - 在 WordPress i18n 中,“_x”和添加评论有什么区别?
- reactjs - 应用程序返回 false 作为值而不是数字
- javascript - 如何使用 Angular 在 http 请求中添加延迟?
- opengl - 当多个纹素处于相等距离时,在纹理的点采样期间返回哪个纹素值?
- redis - 使用 redis 排序集来维护顶级用户的上限列表(按分数)
- c - 质因数之和
- java - 来自构建 Java 程序帮助的 Java 继承示例 - 找不到符号
- java - 解析发射器 LibGDX ParticleEffects 时出错