【问题标题】:Problems with FromFormAttribute and deserialization in AspNet Core 3.1 ApiAsp Net Core 3.1 Api 中的 FromForm 属性和反序列化问题
【发布时间】:2020-10-30 21:38:34
【问题描述】:

我使用 Newtonsoft 反序列化器并尝试在此方法中发送数据(使用 FromFormAttribute):

[HttpPut("test")]
public IActionResult Test([FromForm] MyClass Test) {           
    return Ok();
}

还有,我有课:

public class MyClass
{
    public int Id { get; protected set; }
    public string Text { get; protected set; }

    public MyClass(int id, string text) {
        Id = id;
        Text = text;
    }
}

当我尝试在 HttpPut 方法中发送数据时,我得到了

System.InvalidOperationException: Could not create an instance of type 'MyClass'. 
Model bound complex types must not be abstract or value types and must have a parameterless constructor.
Alternatively, give the 'test' parameter a non-null default value.

我没有创建无参数构造函数并使用受保护的设置器,因为它可以在使用 FromBodyAttribute 的其他方法中正常工作。
我做错了什么?

【问题讨论】:

  • 去掉构造函数和protected关键字。
  • @arcticwhite 可以正常工作,但我必须具有受保护的属性和带参数的公共 ctor
  • 你的错误是说你必须有无参数的构造函数。
  • @arcticwhite 对不起,我不明白你的意思。我没有说我必须有无参数的ctor。我只是说我需要具有参数和受保护属性的公共 ctor
  • 我们能知道具体原因吗?我们会想一个解决方案来保护它并且还有一个构造函数,但是我们可以有更多的上下文......

标签: c# api asp.net-core deserialization asp.net-core-webapi


【解决方案1】:

只需添加一个无参数构造函数

 public class MyClass
        {
            public int Id { get; set; }
            public string Text { get; set; }
            

            public MyClass()
            {
            }
            public MyClass(int id, string text)
            {
                Id = id;
                Text = text;
            }
        }

【讨论】:

  • 无参数 ctor 根本不必公开
  • 它将序列化,但使用默认值:Id 为 0,Text 为 null
  • @zolty13 with protected ctr 将反序列化错误
  • @hernantos 那么默认值有什么问题?你想让我做什么? FromForm 没有使用您的自定义承包商
猜你喜欢
  • 2020-08-28
  • 1970-01-01
  • 2018-06-21
  • 2021-03-15
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
相关资源
最近更新 更多