Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Output formatters order

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?

like image 926
TheDoomDestroyer Avatar asked Sep 20 '25 00:09

TheDoomDestroyer


1 Answers

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.

like image 156
Marc Gravell Avatar answered Sep 21 '25 14:09

Marc Gravell