Search code examples
c#json.net.net-core

.Net core 3.0 API doesn't bind properties with hyphen


Reviewed the question as it was not received well the last time. Hope I have provided all the required information below.

I have a basic API controller and my Json object doesn't seem to bind to the model properly. The root object binds but the property with hyphen in its name doesn't bind. Unfortunately, I cannot drop the hyphen in the property name.

How do I get the property to bind correctly?

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace TestCoreAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        // POST: api/Test
        [HttpPost]
        public string Post([FromBody] TestPayload testPayload)
        {
            if (testPayload == null)
            {
                return "Test payload is empty";
            }

            if (string.IsNullOrWhiteSpace(testPayload.TestProperty))
            {
                return "Test property is empty";
            }

            return "Valid input - " + testPayload.TestProperty;
        }
    }

    [JsonObject("test-payload")]
    public class TestPayload
    {
        [JsonProperty(PropertyName = "test-property")]
        public string TestProperty { get; set; }
    }
}

This is the call I'm making to the API

POST /api/test HTTP/1.1
Content-Type: application/json

{"test-property":"some string value"}

Solution

  • Are you adding AddNewtonsoftJson() to your services in Startup.ConfigureServices ? If not, the new System.Text.Json is being used, not Newtonsoft. I think you'll need to do AddNewtonSoftJson() as i'm fairly sure System.Text.Json doesn't support 'kebab case' bindings.

    https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#newtonsoftjson-jsonnet-support