简体   繁体   中英

Model population fails on HttpPost of JSON body

I am running into an issue where when posting a JSON to a .NET 6 controller method. The the Model isn't being populated with the data from the post.

For example, a snippet of the JavaScript that sends the data:

let content = {
    asset: {
        id: item.dataset.itemId,
        title: item.dataset.itemTitle,
        contentType: item.dataset.contentType,
        contentAction: item.dataset.itemAction,
        modified: item.dataset.modifiedDate,
        created: item.dataset.createdDate
    },
    user: {
        username: userElement.dataset.username
    },
    interacted: moment().format('YYYY-MM-DD HH:mm:ss')
}

let response = fetch('/Analytics/Log', {
    method: 'POST',
    mode: 'same-origin',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
    redirect: 'follow',
    referrerPolicy: 'no-referrer',
    body: JSON.stringify(content)
}); 

... this sends to the following Controller:

[HttpPost, HttpOptions]
[Route("/Analytics/Log")]
public IActionResult Log([FromBody] Content body)
{
    AnalyticsExtensions.LogActivity(body);
}

unfortunately, body is always coming across as null. If I change the type to dynamic, I do see an object come across with data, so the data is getting sent -- just not loaded into the model.

... and here is a snippet of the Model:


public class Content
{
    [JsonProperty("asset")]
    public Asset Asset { get; set; }
    
    [JsonProperty("user")]
    public User User { get; set; }
    
    [JsonProperty("interacted")]
    public DateTime Interacted { get; set; }
}

public class Asset 
{
    [JsonProperty("id")]
    public Guid ID { get; set; }

    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonProperty("contentType")]
    public string ContentType {get; set; }
    
    [JsonProperty("contentAction")]
    public string ContentAction { get; set; }
    
    [JsonProperty("modified")]
    public DateTime Modified { get; set; }
    
    [JsonProperty("created")]
    public DateTime Created { get; set; }
}

public class User 
{
    [JsonProperty("username")]
    public string Username { get; set; }
}

I have checked for obvious spelling errors and decorated the model with JsonProperty decorations, but still nothing...

I realize this is likely something stupid, but an extra set of eyes would be appreciated.

Actually, I found the issue was with this line:

interacted: moment().format('YYYY-MM-DD HH:mm:ss')

This is not considered a valid date format for JSON.

Changing it to the following appears to have corrected the issue:

interacted: moment().format('YYYY-MM-DDTHH:mm:ss')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM