web-api POST body object always null

前端 未结 26 2801
余生分开走
余生分开走 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:13

    In my case the problem was the DateTime object I was sending. I created a DateTime with "yyyy-MM-dd", and the DateTime that was required by the object I was mapping to needed "HH-mm-ss" aswell. So appending "00-00" solved the problem (the full item was null because of this).

    0 讨论(0)
  • 2020-11-27 15:14

    If the any of values of the request's JSON object are not the same type as expected by the service then the [FromBody] argument will be null.

    For example, if the age property in the json had a float value:

    "age":18.0

    but the API service expects it to be an int

    "age":18

    then student will be null. (No error messages will be sent in the response unless no null reference check).

    0 讨论(0)
  • 2020-11-27 15:15

    Seems like there can be many different causes of this problem...

    I found that adding an OnDeserialized callback to the model class caused the parameter to always be null. Exact reason unknown.

    using System.Runtime.Serialization;
    
    // Validate request
    [OnDeserialized]  // TODO: Causes parameter to be null
    public void DoAdditionalValidatation() {...}
    
    0 讨论(0)
  • 2020-11-27 15:17

    Just one more thing to look at... my model was marked as [Serializable] and that was causing the failure.

    0 讨论(0)
  • 2020-11-27 15:19

    I was also trying to use the [FromBody], however, I was trying to populate a string variable because the input will be changing and I just need to pass it along to a backend service but this was always null

    Post([FromBody]string Input]) 
    

    So I changed the method signature to use a dynamic class and then convert that to string

    Post(dynamic DynamicClass)
    {
       string Input = JsonConvert.SerializeObject(DynamicClass);
    

    This works well.

    0 讨论(0)
  • 2020-11-27 15:19

    Just to add my history to this thread. My model:

    public class UserProfileResource
    {
        public Guid Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Phone { get; set; }
    
        public UserProfileResource()
        {
        }
    }
    

    The above object couldn't be serialized in my API Controller and would always return null. The issue was with Id of type Guid: everytime I passed empty string as an Id (being naive that it will automatically be converted to Guid.Empty) from my frontend I received null object as [FromBody] paramether.

    Solution was either to

    • pass valid Guid value
    • or change Guid to String
    0 讨论(0)
提交回复
热议问题