Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

How to set OutputFormatters in RTM #4965

Closed
Lutando opened this issue Jul 5, 2016 · 4 comments
Closed

How to set OutputFormatters in RTM #4965

Lutando opened this issue Jul 5, 2016 · 4 comments
Labels

Comments

@Lutando
Copy link

Lutando commented Jul 5, 2016

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;
})
@javiercn
Copy link
Member

javiercn commented Jul 5, 2016

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.

@nil4
Copy link

nil4 commented Jul 5, 2016

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.

@rynowak
Copy link
Member

rynowak commented Jul 5, 2016

@nil4 - if this is missing we should add it. #4967

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

@javiercn
Copy link
Member

javiercn commented Jul 5, 2016

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.

services.AddMvcCore()
   .AddJsonOptions(options => ... )

The right thing to do would be

services.AddMvcCore()
   .AddJsonFormatter()
   .AddJsonOptions()

And at that point it will be simpler just to do

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

6 participants