Muhammad Rehan Saeed
Muhammad Rehan Saeed

Reputation: 38507

Configuring JsonOutputFormatter using AddMvcCore

I'm trying to setup a slimline ASP.NET Core pipeline and am using AddMvcCore instead of AddMvc. I've copied this mostly from AddMvc, omitting the Razor related items:

public void ConfigureServices(IServiceCollection services) =>
    services
        .AddMvcCore(
            options => 
            {
                // JsonOutputFormatter not found in OutputFormatters!
                var jsonOutputFormatter = 
                    options.OutputFormatters.OfType<JsonOutputFormatter>.First();
                jsonOutputFormatter.SupportedMediaTypes.Add("application/ld+json");
            })
        .AddApiExplorer()
        .AddAuthorization()
        .AddFormatterMappings()
        .AddRazorViewEngine()
        .AddRazorPages()
        .AddCacheTagHelper()
        .AddDataAnnotations()
        .AddJsonFormatters()
        .AddCors();

I want to add a MIME type to the JsonOutputFormatter but it can't be found in the OutputFormatters collection. That said, the app can still output JSON, so I think the JsonOutputFormatter is being added at a later time. How can I get hold of the JsonOutputFormatter?

Upvotes: 4

Views: 1475

Answers (2)

Muhammad Rehan Saeed
Muhammad Rehan Saeed

Reputation: 38507

You can use AddMvcOptions at the end (position is important) to access the JSON formatters after they have been added:

services
    .AddMvcCore()
    .AddJsonFormatters()
    .AddMvcOptions(options => { // do your work here });

Upvotes: 2

Cristian Szpisjak
Cristian Szpisjak

Reputation: 2479

public void ConfigureServices(IServiceCollection services) =>
services
    .AddMvcCore(
        options => 
        {
            var jsonOutputFormatter = options.OutputFormatters.FirstOrDefault(p => p.GetType() == typeof(JsonOutputFormatter)) as JsonOutputFormatter;

            // Then add
            jsonOutputFormatter?.SupportedMediaTypes.Add("application/ld+json");
        })
    .AddApiExplorer()
    .AddAuthorization()
    .AddFormatterMappings()
    .AddRazorViewEngine()
    .AddRazorPages()
    .AddCacheTagHelper()
    .AddDataAnnotations()
    .AddJsonFormatters()
    .AddCors();

Upvotes: 1

Related Questions