ASP.NET Web API deep model binding

拥有回忆 提交于 2019-12-25 04:22:39

问题


I've noticed (even in Web API 2.1) that deep parameter types get filled (processed by the model binder) only on the first level. That is :

public class Person
{
    public string Name { get; set; }
    public PersonDetails Details { get; set; }
}

public class PersonDetails
{
    public string Address { get; set; }
    public int Age { get; set; }
}

// ...

public class PersonController : ApiController
{

    [HttpPost]
    public void ProcessPerson(Person person)
    {
        // person.Name is filled in correctly
        // person.Details.Address and person.Details.Age are not filled in correctly. That is, they have default values (null and 0)
    }
}

Is there a simple solution for this problem, except flatting out the Person class like so ?

public class PersonData
{
    public string Name { get; set; }
    public string Address { get; set; }
    public int Age { get; set; }   
}

Later edit 1 :

  1. If I flatten the Person class I get all the data correctly
  2. The request is made by POST (and not GET) because I need to ensure there is no caching and since the operation alters state it would be semantically incorrect to use GET

来源:https://stackoverflow.com/questions/22203989/asp-net-web-api-deep-model-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!