我想用 GET 方法绑定(bind)不可变模型。它适用于 POST。为什么?
[HttpGet]
public string Get([FromQuery]Something something)
{
return "value";
}
[HttpPost]
public void Post([FromBody]Something something)
{
}
public class Something
{
public string Prop1 { get; }
public int Prop2 { get; }
public Something(string prop1, int prop2)
{
Prop1 = prop1;
Prop2 = prop2;
}
}
使用 GET 方法我得到异常:
InvalidOperationException: Could not create an instance of type WebApplication2.Something;. Model bound complex types must not be abstract or value types and must have a parameterless constructor.
它是否与[FromQuery] 和[FromBody] 属性有关?
请您参考如下方法:
[FromBody] 属性标志到 MVC 管道,以使用配置的格式化程序从请求主体绑定(bind)数据。根据请求的内容类型选择格式化程序。
JsonInputFormatter 是默认格式化程序,基于 Json.NET,它只是执行 JSON 字符串正文反序列化 (code):
model = jsonSerializer.Deserialize(jsonReader, type);
因为在反序列化过程中,对象的构造函数没有被调用,你没有任何像“必须有一个无参数构造函数”这样的错误。
相反,对于[FromQuery]Something ComplexTypeModelBinder被使用,它首先通过调用默认构造函数创建您的 Something 类的实例,然后将相应的值分配给公共(public)属性。检查BindModelCoreAsync method for implementation details .
