WebAPI 2不会反序列化List< string> POST请求中FromBody对象的属性 [英] WebAPI 2 not deserializing List<string> property of FromBody object in POST request

查看:424
本文介绍了WebAPI 2不会反序列化List< string> POST请求中FromBody对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In one of my WebAPI 2 applications, I'm having trouble deserializing a List<string> property of a FromBody object. (The list stays empty, while the other properties are deserialized correctly.)

无论我做什么,如果将属性更改为string[],则该属性似乎只能正确反序列化.对我来说不幸的是,该属性必须为List<string>类型.

Whatever I do, the property only seems to deserialize correctly if I change the property to a string[]. Unfortunately for me, the property needs to be of type List<string>.

根据我发现的另一个问题,我应该只要T不是Interface,就可以反序列化为List<T>.

According to another question I found, I should be able to deserialize to a List<T>, as long as T is not an Interface.

有人知道我在做什么错吗?

Is there anyone who has an idea what I could be doing wrong?

控制器:

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"
    ]
}

推荐答案

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

With thanks to @vc74 and @s.m. , I managed to update my project object class to look like the following to make it work the way I want it to:

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
}

而不是尝试防止从获取值,而是不得不阻止设置该值到.

Instead of trying to prevent getting a null value from Comments, I had to prevent setting the value to null.

这篇关于WebAPI 2不会反序列化List&lt; string&gt; POST请求中FromBody对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆