将嵌套集合发布到Web API

4

我将尝试向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时,为什么会得到零长度集合?这个实现是错误的吗?我该如何使其正常工作?

你能展示一下 API 控制器吗? - Lior Dadon
我刚刚将API控制器代码添加到问题主体中。 - caranhithion
1个回答

6
我认为您需要创建一个类似于这样的模型绑定器:
Post([ModelBinder(typeof(MyClassModelBinder))] MyClass myClass)

请阅读以下文章了解如何操作: ASP.NET Web API中的参数绑定


谢谢@Lior。我一直在避免使用自定义模型绑定器,但可能我没有其他选择了。我会尝试创建一个。 - caranhithion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接