Based on some value in the request (header or in the url) I want to change the serialization of my DTO objects.
Why? Well I\'ve applied the [JsonProperty(\"A\")]
Here are two options:
Options you set by services.AddMvc().AddJsonOptions()
are registered in DI and you can inject it into your controllers and services:
public HomeController(IOptions optionsAccessor)
{
JsonSerializerSettings jsonSettings = optionsAccessor.Value.SerializerSettings;
}
To per-request override these serialization settings, you could use Json
method or create JsonResult
instance:
public IActionResult Get()
{
return Json(data, new JsonSerializerSettings());
return new JsonResult(data, new JsonSerializerSettings());
}
public class ModifyResultFilter : IAsyncResultFilter
{
public ModifyResultFilter(IOptions optionsAccessor)
{
_globalSettings = optionsAccessor.Value.SerializerSettings;
}
public async Task OnResultExecutionAsync(
ResultExecutingContext context,
ResultExecutionDelegate next)
{
var originResult = context.Result as JsonResult;
context.Result = new JsonResult(originResult.Value, customSettings);
await next();
}
}
Use it on action/controller:
[ServiceFilter(typeof(ModifyResultFilter ))]
public IActionResult Index() {}
Or create a custom attribute as described in documentation:
[ModifyResultAttribute]
public IActionResult Index() {}
Don't forget to register the filter in DI.