0

I am writing an application in ASP.NET Core WebApi. Given the tools provided by the framework, what is the best mechanism to use in order to inspect and change object property values during serialization?

Specifically what I need to do is perform a translation on, for example, a string value for a particular property if it meets certain criteria (for my app I'm using custom annotations to mark properties that need to be acted upon).

I assumed a ContractResolver would do the trick, but it appears to only work on Types rather than the object instance itself.

Additionally, I don't want to manually call a serialization method for this. This needs to be part of the WebAPI processing pipeline so I assume gets placed within the AddJsonOptions within Startup.cs.

Jake Shakesworth
  • 3,335
  • 4
  • 29
  • 43
  • You are using `Ok()` method of `ApiController` base class which all controllers inherit from. So why not create your own `MyApiController` and override `OK(data)` method which will change/translate values of required properties. From responsibilities point of view - you are changing values - so this logic should be some how explicitly visible for readers of your code. If you hide it inside request pipeline some other developers can be confused because of changed values in the actual response. – Fabio Jun 24 '17 at 16:44
  • 2
    You mean, something like this? [How can I encrypt selected properties when serializing my objects?](https://stackoverflow.com/q/29196809/3744182). Or this? [json serializer NullValueHandling without use datamember attribute](https://stackoverflow.com/q/32787256/3744182). – dbc Jun 24 '17 at 18:13

0 Answers0