我的控制器中有该发帖请求:
[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;
}
非常感谢您!
答案 0 :(得分:1)
为使模型绑定正常工作,属性get
和set
上的访问器应为默认值,公共属性为public
。将访问器设置为private
,internal
或protected
将导致模型绑定失败。
在大多数情况下,您甚至都不会出错。属性将仅显示属性数据类型的默认值。
模型绑定程序正在使用来自外部源的数据设置属性,因此需要公开访问它们。