1

In my REST API, my model binding is not mapping a property that is a list of objects. It correctly gets to the controller, and shows all the properties but they are empty.

E.g. for the POST request {age: 202, setting: ["school"]} I get something like this in the response:

Got param type=SearchStringDTO; param={"age":202,"setting":[]}

I want it to respond with something like this:

Got param type=SearchStringDTO; param={"age":202,"setting":["school":true, "hospital":false]}

How can I guide it to parse the setting parameter into a List<Setting> ?

Here is the controller:

using System.Web.Http;
...
        [HttpPost]
        public HttpResponseMessage Index(SearchStringDTO param) {
            return ResponseMessage(this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Got param type= " + param.GetType() + "; param = " + JsonConvert.SerializeObject(param)));

        }

Here is the model:

    public sealed class SearchStringDTO {
        public int age { get; set; }

        public List<Setting> setting { get; set; }
    }

Here is the Setting class:

    public class Setting {
        public bool hospital { get; set; }
        public bool school { get; set; }
    }

I started down this path to parse things out manually, but it's a nightmare of JObject, JToken, JArray stuff.

        [HttpPost]
        public IHttpActionResult Index(Newtonsoft.Json.Linq.JObject param) {
            return ResponseMessage(this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Got param type= " + param.GetType() + "; param = " + JsonConvert.SerializeObject(param)));
        }

Maybe I need a custom bind model? I got lost trying to figure out how to build and use one.

bitwise
  • 13
  • 4

1 Answers1

0

Your code is ok, but your json input parameter is not in a correct format. I tested

[HttpPost]
public string Index( [FromBody] SearchStringDTO param)
{
return "Got param type= " + param.GetType()
 + "; param = " + JsonConvert.SerializeObject(param);
}

in postman using:

 {age: 202, setting: [{"school":false, "hospital":true},{"school":true, "hospital":false}]}

and got output :

Got param type= SearchStringDTO; param = {"age":202,"setting":[{"hospital":true,"school":false},{"hospital":false,"school":true}]}
Serge
  • 40,935
  • 4
  • 18
  • 45