1

I am migrating an Asp.Net Core 2.2 Web Api to 3.1

I noticed that now System.Int32 are now serialized into strings by System.Text.Json

Before (2.2):

{id: 1, ..}

After (3.1) :

{id: "1", ..}

Edit id is an int property in C#

So the Js consuming the web api needs to be changed - pretty heavy migrations that I am not hurried to do.

I found options for :

  1. Keeping NewtonSoft Json.Net for serialization

    It is a solution. But I 'd like to keep up to date with the latest technologies !

  2. Providing a custom converter for integers

    It doesn't seem to work in my case

Is there a way to tell the new Json Serializer in System.Text.Json to serialize integers as 42 not "42" ?

Emmanuel DURIN
  • 4,803
  • 2
  • 28
  • 53
  • In my opinion you should examine your Startup class. I made project for .net core 3.1 with web api template and I receive from controller int values as int, not string. – Lukasz Szczygielek Feb 03 '20 at 18:24
  • Can you provide more information about the API and the model you are serializing? Is `id` actually `int32` or is it a string/object or some other type? Do you have some custom converter registered? `S.T.Json` outputs ints as numbers, not string. – ahsonkhan Feb 03 '20 at 19:01
  • Can't reproduce in a standalone console app, see https://dotnetfiddle.net/svwxd4. Can you please share a [mcve]? What is true is that, unlike Json.NET, `System.Text.Json` will not automatically deserialize a `string` to an `int`, but that's not the problem you are describing. – dbc Feb 03 '20 at 19:14
  • @ahsonkhan : just made an edit that my property is an int – Emmanuel DURIN Feb 03 '20 at 19:18
  • @dbc : thanks for the work. I actually saw examples from Ms that Don't have my "bad behavior" - so I am still wondering. – Emmanuel DURIN Feb 03 '20 at 19:21

1 Answers1

0

After reading advice from Hostel and checking from a new Web Api ASP.NET Core 3.1 app and seeing expected behavior, I compared my Startup.cs to the one of Visual Studio template app.

I just added in Startup.ConfigureServices

services.AddControllers();

Despite the lack of that missing service, the controllers "worked", but not as expected.

Maybe because of the presence of another extension method that added other services.

Thanks to all for your careful reading, remarks and questions

Emmanuel DURIN
  • 4,803
  • 2
  • 28
  • 53