Cameron
Cameron

Reputation: 2594

WebApi Not Deserializing Correctly

I'm at my wit's end here. I think I just need another set of eyes.

Method Signature:

public async Task<IHttpActionResult> Post(ApiRequest request)

Model:

[SuppressMessage("ReSharper", "CollectionNeverUpdated.Global")]
[SuppressMessage("ReSharper", "AutoPropertyCanBeMadeGetOnly.Global")]
public class ApiRequest
{
    [JsonProperty("allowLoadingToDataWarehouse")]
    public bool AllowLoadingToDataWarehouse { get; set; } 

    [JsonProperty("initialDelay")]
    public string InitialDelay { get; set; } 

    [JsonProperty("reportIds")]
    public IEnumerable<string> ReportIds { get; set; }

    [JsonProperty("reportTypeDelay")]
    public string ReportTypeDelay { get; set; } 

    [JsonProperty("runType")]
    [JsonConverter(typeof(StringEnumConverter))]
    public ReportRunType RunType { get; set; } 

    [JsonProperty("userId")]
    public string UserId { get; set; } 

    [JsonProperty("wwDelay")]
    public string WWDelay { get; set; }

    [JsonProperty("weeks")]
    public IEnumerable<string> Weeks { get; set; }
}

Javascript:

   var submitReportRequest = {
        userId: userid,
        reportIds: reportids,
        runType: 'Custom',
        weeks: selectedweeks,
        initialDelay: $('#InitialDelay').val(),
        reportTypeDelay: $('#ReportTypeDelay').val(),
        wwDelay: $('#WWDelay').val(),
        allowLoadingToDataWarehouse: $('#AllowLoadingToDataWarehouse').val()
   };

   $.post("/api/SubmitReport", JSON.stringify(submitReportRequest), function (data) {
        alert('success');
   });

Serialized Json From JavaScript Post:

{
  "userId": "30",
  "reportIds": [
    "59",
    "60",
    "61",
    "62",
    "63",
    "64"
  ],
  "runType": "Custom",
  "weeks": [
    "201409",
    "201410",
    "201411",
    "201412"
  ],
  "initialDelay": "00:00:00",
  "reportTypeDelay": "00:00:00",
  "wwDelay": "00:00:00"
}

Quickwatch of Deserialized Object Quickwatch of Deserialized Object

Initially I had int and TimeSpan for the Ids and Delays, respectively, and those were not deserializing correctly. So I changed them all to strings, and they're still not deserializing correctly.

What am I doing wrong or missing?

Edit: After trying every combination of attributes, I finally decided to stick it into the Fiddler Composer. And it works. So something must be off with my JavaScript.

Upvotes: 0

Views: 322

Answers (1)

Cameron
Cameron

Reputation: 2594

Turns out that shorthand JQuery post() method was setting the Content-Type attribute on the Request to application/x-www-form-urlencoded; charset=UTF-8 when it needed to be set to application/json; charset=UTF-8

I found by watching the Network traffic in Chrome, and by changing my javascript to this answer.

Upvotes: 2

Related Questions