I want to use different JSON Output Formatters for different Routes or Controllers. The default and a custom json output formatter
Startup.cs
services.AddControllers(options =>
{
options.RespectBrowserAcceptHeader = true;
options.OutputFormatters.Add(new CustomJsonMediaFormatter());
});
CustomJsonMediaFormatter
public class CustomJsonMediaFormatter : TextOutputFormatter
{
public JsonMediaFormatter()
{
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/vnd.XYZ+json"));
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
}
protected override bool CanWriteType(Type type)
{
return true;
}
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
// my code
}
}
Controller A
[ApiController]
[Produces("application/vnd.XYZ+json")]
public class AController : BaseController
{
[HttpGet]
public async Task<IActionResult> Get()
{
// return an object
}
}
Controller B
[ApiController]
[Produces("application/json")]
public class BController : BaseController
{
[HttpGet]
public async Task<IActionResult> Get()
{
// return an object
}
}
When I fire a request to the A Cotroller with Postman it is not using my Custom Output Formatter. It is still using the default JSON Output Formatter.
It seems that it takes the first JSON Output Formatter in the list. I tried to clear the output formatter list and add my custom json formatter. Then it is always using the custom formatter.
What I want to do with the custom output formatter is: I want to remove some fields from objects that the user is not allowed to see, depending on configuration. But only for some API Controllers and not all.