【问题标题】:Not able to post data to web api controller action using FromBody Attribute无法使用 FromBody 属性将数据发布到 Web api 控制器操作
【发布时间】:2018-06-07 07:27:26
【问题描述】:

客户端模型(类型脚本文件):

export  interface IRecord {
    id: string
    amount: string,
    amountConst: string,
    amountLC: string,   
}

服务器端模型/类:我正在使用 newtonsoft json。

如果我将 Json 属性值更改为 typescript 文件中的属性名称,那么 该列值在 UI 上不可见。

public class Records
{
    [Key]
    public string ID { get; set; }
    [Column("Amount")]
    [JsonProperty("Amount")]
    public string Amount { get; set; }

    [Column("Amount Const $")]
    [JsonProperty("Amount Const $")]
    public string AmountConst { get; set; }

    [Column("Amount LC")]
    [JsonProperty("Amount LC")]
    public string AmountLC { get; set; }
}

Web API 控制器:

[HttpPost]
[Route("Export")]
[ActionName("Export")]
public FileResult Export([FromBody]List<Records> Record)
{
    try
    {
    }
}

服务器端我正在从客户端获取准确的记录数 但具有 null 属性值。

【问题讨论】:

  • 您应该在任何地方删除JsonProperty 并以角度修复您的绑定以使用没有空格的版本。当您添加带有空格的 JsonProperty 时,ASP.NET Core 需要像 [{ "Amount": 5, "Amount Const $": "abc", "Amount LC": "xyz" }] 这样的 json 主体,但您的 Angular 客户端会发送 [{ "amount": 5, "amountConst": "abc", "amountLC": "xyz" }]
  • @Tseng 我正在使用合同解析器将属性名称转换为 Typescript 文件中的名称,将 Pascalcase 转换为 camelcase

标签: c# json asp.net-core .net-core asp.net-core-mvc


【解决方案1】:

要使其正常工作,您应该更改发送客户端模型或服务器端绑定的方式。

如果您指定 [JsonProperty] 属性,则 JSON 反序列化程序会期望 JSON 属性名称与 propertyName 参数的值完全相同。

对于您的情况,您发送的模型应如下所示

[{
    "ID": "11",
    "Amount": "1",
    "Amount Const $": "1.0",
    "Amount LC": "aaa"
}]

接口IRecord 无法使用,因为它无法绑定到服务器端模型。

因此,您有多种选择可以让它发挥作用:

  • 删除IRecord接口并发送具有如上所示结构的对象
  • 更改服务器端模型,使两个模型的属性匹配
  • Records 类型(请check this)编写自定义模型绑定器来处理您的案例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多