Changing JsonSerializerSettings in API Controller

I am creating a basic WebAPI controller from which most of my controllers will come in. This controller will have to change the JsonSerializerSettings settings by adding a specific Json Contract recognizer.

It is important that I do this in the controller itself, because during the creation of the Contract, I need access to the HttpRequest as well as the injected service.

Currently I am just overriding the Ok (object value) method:

  public override OkObjectResult Ok(object value)
  {
     var resolver = new TranslationContractResolver(_translationService, language);

     // serialize the object, and in doing so will translate all translatable properties.
     string json = JsonConvert.SerializeObject(
        value,
        Formatting.None,
        new JsonSerializerSettings { ContractResolver = resolver });

     // now, deserialize back so we can respect content requests (XML, etc).
     Type type = value.GetType();
     var deserializedBack = JsonConvert.DeserializeObject(json, type);

   return base.Ok(deserializedBack);

      

It works, but I'm pretty sure I'm successful.

I would like to add a contract recognizer to the OnActionExecuting method, but I don't know how to properly access the JsonOptions configuration. I was able to get the IServiceProvider from the HttpContext, then grab the IOptions (JsonOptions) from the provider and overwrite the SerializationSettings directly. But this seems to be very hacky and seems to keep this setting for responses in other controllers after that.

+3


source to share





All Articles