Mvc: How to set OutputFormatters in RTM

Created on 5 Jul 2016  路  4Comments  路  Source: aspnet/Mvc

How do I assign the various OutputFormatter members if they are now private members? in RC2 they were not

services.AddMvc(options =>
{
     var formatter = options.OutputFormatters.First(f => f is JsonOutputFormatter) as JsonOutputFormatter;
     formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 
     formatter.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
     formatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
})
question

All 4 comments

You should call AddJsonOptions to configure the formatters settings you want to configure them. See https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Formatters.Json/DependencyInjection/MvcJsonMvcBuilderExtensions.cs and https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Formatters.Json/MvcJsonOptions.cs

This will configure the settings for the input and the output formatters. If you want to configure only the settings for the output formatter you should remove the existing onE, new up another and add it to the list of output formatters in MVC options. Hope this helps.

Is there a good reason why the AddJsonOptions method isn't an extension on IMvcCoreBuilder as opposed to IMvcBuilder? I think JSON output options are equally important (if not more so) for API-focused projects where MVC Core is sufficient.

@nil4 - if this is missing we should add it. https://github.com/aspnet/Mvc/issues/4967

You can do everything AddJsonOptions does by passing a delegate to AddJsonFormatter

I think in the AddMvcCore case its better to configure it when you call to AddJsonFormatter instead of adding another AddJsonOption method on IMvcCoreBuilder. The reason for this is that the following chain would be valid but produce an incorrect configuration.

``` C#
services.AddMvcCore()
.AddJsonOptions(options => ... )


The right thing to do would be

``` C#
services.AddMvcCore()
   .AddJsonFormatter()
   .AddJsonOptions()

And at that point it will be simpler just to do

C# services.AddMvcCore() .AddJsonFormatters(settings => ...)

Was this page helpful?
0 / 5 - 0 ratings