1

I've added the following code to my Startup.cs:

services.AddControllers().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
});

However, this feels like a breaking change. The main reason for adding it was to remove the need for lots of null checks against request properties everywhere in the controllers. However, it also has the effect of doing it for the reverse i.e. removing properties in the response that are null. So if I understand this correctly it will mean any other apps that currently hit the api and check the response properties for null will now break as those properties won't exist in the response when they're null.

So is there a way to conditionally set this flag by api version? I don't want to go down the route of setting it per property or somehow setting this property on all relevant controllers.

sr28
  • 4,728
  • 5
  • 36
  • 67
  • How are you doing API versioning? – DavidG Jun 01 '22 at 08:36
  • @DavidG - As part of the uri like this "api/v{version:apiVersion}/someRoute". – sr28 Jun 01 '22 at 08:39
  • That's not what he's asking. Are you using swagger? Or mvc.versioning? Or something else. And why are you using json.net instead of the preferred system.text.json? – JHBonarius Jun 01 '22 at 08:53
  • @JHBonarius - using swagger. That said, I've spotted a line that says services.AddApiVersioning(), which by the looks of it is Microsoft.AspNetCore.Mvc.Versioing. As for using json.net, it's what's there now, not my choice. – sr28 Jun 01 '22 at 09:13
  • If you add the code to the startup.cs it's a global setting: i.e. it's applied everywhere. If you want to have discrepancy between api versions, I think you have to implement that manually: the serialization Middleware will have to be made aware of the API version. – JHBonarius Jun 01 '22 at 10:39
  • @JHBonarius - that was my thought. However, if there's a way to apply it at the global level like this, but then override it at the controller level on the controllers I don't want using it, that would be the next best thing. I'll see if I can get that working. – sr28 Jun 01 '22 at 10:56
  • 2
    *if there's a way to apply it at the global level like this, but then override it at the controller level on the controllers I don't want using it, that would be the next best thing* -- then does [Change the JSON serialization settings of a single ASP.NET Core controller](https://stackoverflow.com/q/52605946/3744182) answer your question? – dbc Jun 02 '22 at 14:15
  • @dbc - thanks for the link. I'll give that a go and see if I can get it working. – sr28 Jun 06 '22 at 16:42
  • @dbc That totally worked for me. The link contains core2 and core3, with Net6 awaiting editing udpate. – kipras Aug 04 '23 at 16:05
  • @kipras - I voted to approve, but if the edit gets rejected as conflicting with the author's intent, you could add it as a new answer. – dbc Aug 04 '23 at 21:46

0 Answers0