WebAPI 2不反序列化List POST请求中FromBody对象的属性

问题描述 投票:0回答:2

在我的一个WebAPI 2应用程序中,我无法反序列化List<string>对象的FromBody属性。 (列表保持为空,而其他属性正确反序列化。)

无论我做什么,如果我将属性更改为string[],该属性似乎只能正确反序列化。不幸的是,该物业需要是List<string>类型。

根据another question I found,只要List<T>不是T,我应该能够反序列化为Interface

有没有人知道我可能做错了什么?

控制器:

public class ProjectsController : ApiController
{
    public IHttpActionResult Post([FromBody]Project project)
    {
        // Do stuff...
    }
}

项目对象类:

public class Project
{
    public string ID { get; set; }
    public string Title { get; set; }
    public string Details { get; set; }

    private List<string> _comments;
    public List<string> Comments 
    { 
        get
        {
            return _comments ?? new List<string>();
        }
        set
        {
            if (value != _comments)
                _comments = value;
        } 
    }

    public Project () { }

    // Other methods
}

请求JSON:

{
    "Title": "Test",
    "Details": "Test",
    "Comments":
    [
        "Comment1",
        "Comment2"
    ]
}
c# asp.net-web-api2 json-deserialization asp.net-apicontroller
2个回答
1
投票

你试过这个吗?

public class Project
{
    public List<string> Comments {get; set;}
    public Project () 
    { 
        Comments = new List<string>();
    }
    ...
}

0
投票

感谢@ vc74和@ s.m. ,我设法将我的项目对象类更新为如下所示,使其按照我希望的方式工作:

public class Project
{
    public string ID { get; set; }
    public string Title { get; set; }
    public string Details { get; set; }

    private List<string> _comments = new List<string>();
    public List<string> Comments 
    { 
        get
        {
            return _comments;
        }
        set
        {
            if (value != _comments)
            {
                if (value == null)
                    _comments = new List<string>();
                else
                    _comments = value;
            }
        } 
    }

    public Project () { }

    // Other methods
}

而不是试图阻止从null获得Comments值,我不得不阻止将值设置为null

© www.soinside.com 2019 - 2024. All rights reserved.