【发布时间】: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