【发布时间】:2016-09-13 21:37:59
【问题描述】:
这是一个艰难的过程。我在从 JSON 绑定模型时遇到问题。我正在尝试以多态方式解析提供的记录,并提供它将解析到的记录类型(我希望将来能够添加许多记录类型)。我尝试在调用端点时使用following example 来解析我的模型,但是此示例仅适用于 MVC,不适用于 Web API 应用程序。
我尝试使用 IModelBinder 和 BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 来编写它。但是我在 System.Web.Http 命名空间中找不到 ModelMetadataProviders 的等价物。
感谢任何人可以提供的任何帮助。
我有一个具有以下对象结构的 Web API 2 应用程序。
public abstract class ResourceRecord
{
public abstract string Type { get; }
}
public class ARecord : ResourceRecord
{
public override string Type
{
get { return "A"; }
}
public string AVal { get; set; }
}
public class BRecord : ResourceRecord
{
public override string Type
{
get { return "B"; }
}
public string BVal { get; set; }
}
public class RecordCollection
{
public string Id { get; set; }
public string Name { get; set; }
public List<ResourceRecord> Records { get; }
public RecordCollection()
{
Records = new List<ResourceRecord>();
}
}
JSON 结构
{
"Id": "1",
"Name": "myName",
"Records": [
{
"Type": "A",
"AValue": "AVal"
},
{
"Type": "B",
"BValue": "BVal"
}
]
}
【问题讨论】:
-
这是我在问题中使用的示例。为这个问题提供的答案是针对 MVC 模型绑定的,我需要 Web API 模型绑定。
标签: c# asp.net .net asp.net-web-api model-binding