首页 > 解决方案 > .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;
}

非常感谢!

标签: asp.net-mvcangularbinding.net-coreasp.net-core-webapi

解决方案


为了使模型绑定正常工作,属性上的访问器getset应该是默认的,它public位于公共属性上。制作访问器private, internal, 或protected将导致模型绑定失败。

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

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


推荐阅读