2

I have a model like

public class DeleteMe
{
    [JsonProperty(PropertyName = "id")]
    public string LalaId { get; set; }

    public string Other { get; set; }
}

I want to be able to send a post request to an API action defined like

[HttpPost]
public async Task<IActionResult> Lala(DeleteMe requestPayload)
{
    // do stuff
}

with the post body being

{
    "id": "someID",
    "other": "someOther"
}

However, when I make this request, the id (LalaId) property isn't bound in the API action. If I send it as LalaId, then it works. But I want that property to be both sent to the client side and received from the client side as id.

I'm using .net core 3.1. I know that with core 3, they've switched from Newtonsoft to their own JSON implementation, but in my Startup.cs I have added

services
    .AddControllersWithViews()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ContractResolver = new CustomJsonContractResolver();
        options.SerializerSettings.Converters.Add(new DateTimeToTicksJsonConverter());
        options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    });

Which should force core to use Newtonsoft instead of System.Text.Json, right?

What is the issue here?

Thanks!

Michael Tontchev
  • 909
  • 8
  • 23
  • What's in CustomContractResolver? When I use those, I usually remove all the [JSONProperty] attributes from the model. – clhereistian Jun 16 '22 at 15:28
  • @clhereistian public CustomJsonContractResolver() : base() { this.NamingStrategy = new CamelCaseNamingStrategy(); } protected override JsonDictionaryContract CreateDictionaryContract(Type objectType) { var contract = base.CreateDictionaryContract(objectType); var keyType = contract.DictionaryKeyType; if (keyType.IsEnum) { contract.DictionaryKeyResolver = key => ((int)Enum.Parse(keyType, key)).ToString(); } return contract; } – Michael Tontchev Jun 16 '22 at 15:31
  • @clhereistian I use it for conversion of enum keys in dictionaries – Michael Tontchev Jun 16 '22 at 15:31
  • Is your startup code and your endpoint in the same assembly? In other words, is it possible you are referencing two different Newtonsoft.Json.dll's? – clhereistian Jun 16 '22 at 15:43
  • Do you need `[FromBody]` for `DeleteMe requestPayload`? See e.g. [Confused with FromBody in ASP.NET Core](https://stackoverflow.com/a/58156463). – dbc Jun 16 '22 at 18:17
  • I teseted with your codes and it works well,have you missed any codes related or installed wrong package? – Ruikai Feng Jun 17 '22 at 06:12
  • @clhereistian all one assembly – Michael Tontchev Jun 17 '22 at 15:13
  • @dbc I think FromBody is only needed when you want to change the default behavior, which is that primitive vars like string come from the URL, and objects come from the body. – Michael Tontchev Jun 17 '22 at 15:15

0 Answers0