I have 3 output formatters, one of which is my custom output formatter that should be triggered when SupportedMediaType is Excel (Content-type: application/vnd.ms-excel
).
services.AddControllers(options =>
{
options.OutputFormatters.Add(new ExcelOutputFormatter());; // Excel stylesheet XML
}).AddNewtonsoftJson().AddXmlSerializerFormatters();
However, if my header is Accept: */*
, the application sends me to ExcelOutputFormatter. Is there a way for me to use the JSON output formatter instead of the Excel one by default?
You would need to mimic the approach used by AddNewtonsoftJson
and AddXmlSerializerFormatters
, so that you can chain it after those two; this is relatively simple:
services.AddControllers(options => {})
.AddNewtonsoftJson().AddXmlSerializerFormatters().AddExcelOutputFormatter();
// ...
public static IMvcBuilder AddExcelOutputFormatter(this IMvcBuilder builder)
{
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, ExcelOutputFormatterSetup>());
return builder;
}
class ExcelOutputFormatterSetup : IConfigureOptions<MvcOptions>
{
void IConfigureOptions<MvcOptions>.Configure(MvcOptions options)
{
options.OutputFormatters.Add(new ExcelOutputFormatter());
}
}
This should get the timing correct so that you're at the correct position in the chain.
As a side note: you may also want to add to options.FormatterMappings
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With