web-api POST body object always null

前端 未结 26 2967
余生分开走
余生分开走 2020-11-27 15:03

I\'m still learning web API, so pardon me if my question sounds stupid.

I have this in my StudentController:

public HttpResponseMessage          


        
26条回答
  •  一向
    一向 (楼主)
    2020-11-27 15:29

    Maybe for someone it will be helpful: check the access modifiers for your DTO/Model class' properties, they should be public. In my case during refactoring domain object internals were moved to DTO like this:

    // Domain object
    public class MyDomainObject {
        public string Name { get; internal set; }
        public string Info { get; internal set; }
    }
    // DTO
    public class MyDomainObjectDto {
        public Name { get; internal set; } // <-- The problem is in setter access modifier (and carelessly performed refactoring).
        public string Info { get; internal set; }
    }
    

    DTO is being finely passed to client, but when the time comes to pass the object back to the server it had only empty fields (null/default value). Removing "internal" puts things in order, allowing deserialization mechanizm to write object's properties.

    public class MyDomainObjectDto {
        public Name { get; set; }
        public string Info { get; set; }
    }
    

提交回复
热议问题