vendredi 21 juillet 2017

ASP .NET WebApi 2 sending Json To api with class that has some

API method receive an object of this class:

    public class TestModel
{
    private IEnumerable<string> _list;
    private IEnumerable<string> _list2;

    public IEnumerable<string> List
    {
        get { return _list; }
        set { _list2 = value; }
    }

    public IEnumerable<string> List2
    {
        get { return _list2; }
        set { _list2 = value; }
    }

}

I know that it might looks weird, it is ofc. But inside a C# Code if you will set a new value for any List or List2 you will always set a List2 to a new value. However, if you use that with API:

The API Method:

 [HttpPost]
    public IHttpActionResult Test(TestModel test)
    {
        return Ok(test);
    }

Request JSON:

{
    "List":["asdas", "asdasd"],
    "List2":["qwe", "qwe"],
}

You wuld receive such a response:

{
"list": null,
"list2": [
    "asdas",
    "asdasd",
    "qwe",
    "qwe"
  ]
}

I know that this is not a normal, but I found that by accident and I'm very curious about that how it happens as I use readonly IEnumerable lists and still it's merging two lists into one - why? I'm pretty sure that it comes to serialization, but still cannot guess how it works.

Will be very thankfull for anybody who can explain that and satisfy my curiosity.




Aucun commentaire:

Enregistrer un commentaire