gpt4 book ai didi

asp.net-mvc - .NET Core 2 Web API : [FromBody] nested object was not binded

转载 作者:行者123 更新时间:2023-12-02 20:20:32 25 4
gpt4 key购买 nike

我的 Controller 中有该发布请求:

[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 Controller 时,在 Angular 服务 postSubscription 方法内,模型已完全初始化,在 Web API 端,只有对象的第一级具有值。属性 Payment(嵌套类型 PaymentBindingModel)不为 null,但其属性未初始化,就像未绑定(bind)一样。

如何解决这个问题?

编辑(添加图像)

enter image description here

编辑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;
}

非常感谢!

最佳答案

为了使模型绑定(bind)正常工作,属性的 getset 上的访问器应该是默认的,即 public 上的 public特性。将访问器设置为私有(private)内部 protected 将导致模型绑定(bind)失败。

大多数时候你甚至不会收到错误;属性将仅显示属性数据类型的默认值。

模型绑定(bind)器使用来自外部源的数据设置属性,因此它们需要可公开访问。

关于asp.net-mvc - .NET Core 2 Web API : [FromBody] nested object was not binded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51502641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com