geckos
geckos

Reputation: 6299

Aspnet API controller parameter not deserializing correctly

I'm pretty new to C# and ASP.NET. I have an API controller with this action method:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Mautic.Webhook 
{
    [ApiController]
    [Route("mautic/[controller]")]
    public class WebhookController : ControllerBase
    {
        public WebhookController(ILogger<WebhookController> logger)
        {
            Logger = logger;
        }

        [HttpPost]
        public ActionResult WebhookAction(WebhookRequest data)
        {
            Logger.LogInformation(ObjectDumper.Dump(data.LeadPostDelete));
            return NoContent();
        }

        private ILogger<WebhookController> Logger { get; }
    }
}

And have this definition of WebhookRequest:

using System.Collections.Generic;
using Newtonsoft.Json;

namespace Mautic 
{
    public class ContactWebhookRequest 
    {
        public int id { get; set; }
        public string timestamp { get; set; }
    }

    public class WebhookRequest
    {
       [JsonProperty(PropertyName = "mautic.lead_post_delete")]
       public List<ContactWebhookRequest> LeadPostDelete { get; set; }
       public string timestamp { get; set; }
    }
}

When I receive data in the controller I want it to deserialize to my class but I got null on LeadPostDelete property. Does ASP.NET understand the Newtonsoft JsonProperty attribute? Or do I need to migrate it to System.Text.Json?

Also migrating to System.Text.Json is enough or I will need to deserialize this by hand on my controller?

Upvotes: 0

Views: 536

Answers (2)

user1785960
user1785960

Reputation: 657

If you want avoid refactoring on migrating to 3+ you should to force controllers to use Newtonsoft.Json:

https://dotnetcoretutorials.com/2019/12/19/using-newtonsoft-json-in-net-core-3-projects/

Sorry for My English.

Upvotes: 0

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30375

JsonProperty attribute does exist in both "old" Newtonsoft.Json that was default in .Net Core before version 3. You are probably using the new System.Text.Json that won't understand this attribute out of the box.

You need probably to use the attribute from that namespace. Otherwise ensure that you use the same serialization and attribute anyway.

Upvotes: 1

Related Questions