1

I am trying to set different JsonSerializerOptions for specific controllers. Specifically, I want to set ReferenceHandler = ReferenceHandler.Preserve for those controllers only, and inherit the rest of the serializer options from some static instance.

I'm looking for a way to do this at the controller level, using System.Text.Json on ASP.NET Core 6.0.

I was able to do this for serialization using an Action Filter using this solution: https://stackoverflow.com/a/56127866/2719183, but I haven't been able to find a good solution to implement this for deserialization. For example, https://stackoverflow.com/a/66256442/2719183, does not work for me because it requires an attribute for each parameter.

How do I override an input formatter at the controller level?

OronDF343
  • 528
  • 1
  • 3
  • 14
  • Would writing a custom converter [like this](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to) solve your problem? – mu88 Mar 14 '22 at 14:44
  • @mu88 No, I am not looking to customize the serialization itself. I am looking to set the `JsonSerializerOptions` differently for certain controllers in ASP.NET Core. – OronDF343 Mar 14 '22 at 15:13
  • 1
    Okay, I see your point... the only thing I found so far is `IControllerConfiguration` which was available in the old ASP.NET stack (full framework). Maybe you can dig into the sources and find/build something similar – mu88 Mar 14 '22 at 15:52

1 Answers1

0

There are two problems: serialization and deserialization.

  1. Serialization. This is relatively easy, you have to create action filter and inspect action result, if it is ObjectResult then you can set custom json formatter.

  2. Deserialization/binding. This one is tricky, you'll need custom body binder (which can be configured to use custom json formatter), custom binder provider, custom binder source and custom IControllerModelConvention to selectively override binding source on actions.

This should work for simple scenarios when you don't use other filters or middlewares etc.

I'm not attaching any code, because it will be a dozen of classes.

kemsky
  • 14,727
  • 3
  • 32
  • 51