Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API list is appended rather than overwritten

I have a class with a constructor as follows

public SomeClass
{
    List<string> MyList;
    public SomeClass()
    {
        this.MyList = new List<string>() { "1","2","3" };
    }
}

my ajax post is as follows:

{MyList:["a","b","c"]}

in the conroller I have

public void Post([FromBody]Models.SomeClass example)
    {

        Debug.WriteLine(example.MyList);
    }

the output is:

["1","2","3","a","b","c"]

I expected:

["a","b","c"]

I expect exactly what was posted rather than the initial values with the posted values appended. Not sure what's going on here, why is the initial state of the list not being overwritten?

like image 850
Jesse Adam Avatar asked Nov 16 '25 23:11

Jesse Adam


1 Answers

I ran into that same behavior a couple months back. I concluded what was happening was, as the WebAPI service received a POST request with some data, it would:

  1. Call the type constructor to instantiate a new C# object corresponding to the POST request.
  2. Add (not overwrite) the data from the POST request to the List in this new object.

I know, you can probably infer that from the result, and you illustrated that nicely.

But what I ended up doing is moving out any initial value-setting from the type constructor into a Factory, for situations when I'd need those "default" values set. Then when new() gets called as part of a POST, it returns an empty List, so the values added from the POST are the only values that end up in the object.

like image 125
Arin Avatar answered Nov 19 '25 13:11

Arin