Web Api发布具有泛型列表属性的复杂对象,计数为0
本文关键字:对象 复杂 属性 Api 布具 列表 泛型 Web | 更新日期: 2023-09-27 18:29:22
我有一些非常基本的HttpClient代码,可以归结为:
var criteria = new Criteria() { Name = "TestName" };
criteria.listProperty.Add(new ComplexObject<int>("value", true));
httpClient.PostAsJsonAsync("api/ctl/myAction", criteria)
控制器看起来像这样:
[HttpPost]
public HttpResponseMessage myAction([FromBody]Criteria criteria)
{
return DoSomethingWithIt(criteria);
}
问题是,我在PostAsJsonAsync
上设置了一个断点,我的criteria对象的名称为"TestName",它的listProperty有一个具有"value"和true属性的项。一切如常。
但是控制器上的断点显示了Count为0的条件,同时它仍然显示了条件对象的名称为"TestName"
[HttpPost]
public HttpResponseMessage myAction(Object criteria)
{
var jsonString = model.ToString();
}
jsonString拥有一切,包括具有"value"和true属性的复杂属性。
My Criteria和ComplexObject对象如下所示:
public class SearchCriteria
{
public List<ComplexObject> listProperty { get; set; }
public string Name { get; set; }
}
public class ComplexObject<T> : ComplexObject
{
public T Value { get; set; }
public List<T> Choices { get; private set; }
public ComplexObject<T>(string complexName, bool isRequired, List<T> choices = null)
{
this.ComplexName = complexName;
this.IsRequired = isRequired;
this.Choices = choices;
}
}
public abstract class ComplexObject
{
public string ComplexName { get; protected set; }
public bool IsRequired { get; protected set; }
}
附言:我试过带[FromBody]和不带[FromBody的两个控制器。
正如您所料,答案是,当跨HTTP或反序列化为JSON时,Generic类型会丢失。为了实现这一点,我必须在我的抽象ComplexObject上编写一个自定义解析器(Deserializer),并在SearchCriteria中编写一个迭代器来调用每个listProperty的解析器。
最后,对于共享我的Model名称空间的c#项目之间Web API的使用,这是一个很好的回答。但它比在我的MVC项目中使用剃刀和/或angularjs所需的复杂得多。
如果您在Web API中使用泛型并且有问题,我的建议是重新评估应用程序的哪个部分是漂亮的。您可以有一个可以轻松传递泛型的漂亮后端,或者一个干净的前端,它需要更基本的后端代码来跨http进行序列化。