我将尝试向Web API提交一个复杂类型对象。在Web API端,当方法接收到对象参数时,每个属性都被正确设置,除了那个由ICollection派生的集合。
这里是我的示例类:
public class MyClass
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private MyCollection<string> collection;
public MyCollection<string> Collection
{
get { return collection; }
set { collection = value; }
}
}
public class MyCollection<T> : ICollection<T>
{
public System.Collections.Generic.List<T> list;
public MyCollection()
{
list = new List<T>();
}
public void Add(T item)
{
list.Add(item);
}
public void Clear()
{
list.Clear();
}
public bool Contains(T item)
{
return list.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
list.CopyTo(array, arrayIndex);
}
public int Count
{
get { return list.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
list.Remove(item);
return true;
}
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return list.GetEnumerator();
}
}
以下是我的API控制器:
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public string Post([FromBody]MyClass value)
{
return "The object has " + value.Collection.Count + " collection item(s).";
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
这是我在客户端上的测试方法:
function Test() {
var obj = {
'Id': '15',
'Collection': [{
'': 'item1'
}, {
'': 'item2'
}]
};
$.post(serviceUrl, obj)
.done(function (data) {
alert(data);
});
在Web Api的post方法中,Id变为15,但Collection的长度为0。
但是当我将集合类型从MyCollection改成ICollection时,集合的长度为2。
当我使用MyCollection时,为什么会得到零长度集合?这个实现是错误的吗?我该如何使其正常工作?