2

In my Razor Pages project, I have created this custom JsonConverter

public class MyConverter : JsonConverter<Instant>
{
    public override Instant Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        // implementation
    }

    public override void Write(Utf8JsonWriter writer, Instant value, JsonSerializerOptions options)
    {
        // implementation
    }
}

I applied it to two properties of this object

public class Event
{
    [JsonConverter(typeof(MyConverter))]
    public Instant Start { get; set; }

    [JsonConverter(typeof(MyConverter))]
    public Instant End { get; set; }

    // Other properties
}

OnGet works fine, the model is well serialized.

The problem is when I post this model on the function below, my custom converter is not called at all.

public async Task<IActionResult> OnPost(Event evt)

Here is the form data sent with fetch.

start=2022-03-18&end=2022-03-18

If Start and End properties would be string it maps well.

I don't have any error, nothing. Any idea on what am I doing wrong ?

JuChom
  • 5,717
  • 5
  • 45
  • 78
  • What does the posted JSON look like? Can you share a [mcve]? System.Text.Json is case sensitive by default, see [JsonSerializer.Deserialize fails](https://stackoverflow.com/a/60123515/3744182), are you sure you are matching the case properly? – dbc Mar 25 '22 at 17:41
  • It's not a casing issue, mapping works well I map Start and End to string. The converter works well outside asp.net core. It's like asp.net core ignores the JsonConverter attribute. I'm not sure I can do it with .net fiddle. – JuChom Mar 25 '22 at 17:47
  • 1
    In that case make sure you're not mixing namespaces from Newtonsoft and System.Text.Json. E.g. you may actually be using `Newtonsoft.Json.JsonConverterAttribute` rather than `System.Text.Json.Serialization.JsonConverterAttribute` without realizing it. – dbc Mar 25 '22 at 18:40
  • I already doubled check this one. I'm full System.Text.Json.Serialization. – JuChom Mar 25 '22 at 18:42
  • 3
    Are you sure you are posting **JSON**? The converter is only called for `application/json` content when there is actual JSON in the post body. A JSON serializer or converter will not be called for form data. See e.g. [How to override default deserialization for Controller Action in ASP.NET Core?](https://stackoverflow.com/q/57561398) and [Confused with FromBody in ASP.NET Core](https://stackoverflow.com/q/50771647) which also arose from data being posted as URL encoded rather than as JSON. – dbc Mar 25 '22 at 19:41
  • 1
    You are right, the framework looks for a value converter when it's not json ! Thanks @dbc – JuChom Mar 28 '22 at 13:07

0 Answers0