Web API complex parameter properties are all null

前端 未结 18 1498
长情又很酷
长情又很酷 2020-11-30 04:18

I have a Web API service call that updates a user\'s preferences. Unfortunately when I call this POST method from a jQuery ajax call, the request parameter object\'s proper

相关标签:
18条回答
  • 2020-11-30 05:08

    Maybe it will help, I was having the same problem.

    Everything was working well, and suddently, every properties was defaulted.

    After some quick test, I found that it was the [Serializable] that was causing the problem :

    public IHttpActionResult Post(MyComplexClass myTaskObject)
    {
        //MyTaskObject is not null, but every member are (the constructor get called).
    }
    

    and here was a snippet of my class :

    [Serializable]  <-- have to remove that [if it was added for any reason..]
    public class MyComplexClass()
    {
         public MyComplexClass ()
         {
            ..initiate my variables..
         }
    
         public string blabla {get;set;}
         public int intTest {get;set;
    }
    
    0 讨论(0)
  • 2020-11-30 05:10

    I came across the same issue. The fix needed was to ensure that all serialize-able properties for your JSON to parameter class have get; set; methods explicitly defined. Don't rely on C# auto property syntax! Hope this gets fixed in later versions of asp.net.

    0 讨论(0)
  • 2020-11-30 05:11

    So there are 3 possible issues I'm aware of where the value does not bind:

    1. no public parameterless ctor
    2. properties are not public settable
    3. there's a binding error, which results in a ModelState.Valid == false - typical issues are: non compatible value types (json object to string, non-guid, etc.)

    So I'm considering if API calls should have a filter applied that would return an error if the binding results in an error!

    0 讨论(0)
  • 2020-11-30 05:11

    A bit late to the party, but I had this same issue and the fix was declaring the contentType in your ajax call:

        var settings = {
            HelpText: $('#help-text').val(),
            BranchId: $("#branch-select").val(),
            Department: $('input[name=departmentRadios]:checked').val()
    
        };
    
    $.ajax({
            url: 'http://localhost:25131/api/test/updatesettings',
            type: 'POST',
            data: JSON.stringify(settings),
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                alert('Success');
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
    

    And your API controller can be set up like this:

        [System.Web.Http.HttpPost]
        public IHttpActionResult UpdateSettings([FromBody()] UserSettings settings)
        {
    //do stuff with your UserSettings object now
            return Ok("Successfully updated settings");
        }
    
    0 讨论(0)
  • 2020-11-30 05:12

    In my case problem was solved when i added

    get{}set{}

    to parameters class definition:

    public class PreferenceRequest
    {
        public int UserId;
        public bool usePopups {get; set;}
        public bool useTheme {get; set;}
        public int recentCount {get; set;}
        public string[] detailsSections {get;set;}
    }
    

    enstead of:

       public class PreferenceRequest
        {
            [Required]
            public int UserId;
            public bool usePopups;
            public bool useTheme;
            public int recentCount;
            public string[] detailsSections;
        }
    
    0 讨论(0)
  • 2020-11-30 05:14

    I guess problem is that your controller is expecting content type of [FromBody],try changing your controller to

    public HttpResponseMessage Post(PreferenceRequest request)
    

    and ajax to

    $.ajax({
        type: "POST",
        data: JSON.stringify(request);,
        dataType: 'json',
        contentType: "application/json",
        url: "http://localhost:1111/service/User",
    

    By the way creating model in javascript may not be best practice.

    0 讨论(0)
提交回复
热议问题