Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Json Formatters to MvcCore?

I'm following the next tutorial of IdentityServer4 implementation for API , but I can't call the method AddJsonFormatters() to services.AddMvcCore(). I'm currently configuring the API from an empty template in ASP.NET Core 3.0.0

I have added NuGet package Microsoft.AspNetCore.Mvc.Formatters.Json with no results. Also, I understand that using AddMvc() instead of AddMvcCore() would be a partial solution but I can't use AddAuthorization() on AddMvc()

//code extracted from the link
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();
    }
}

This is the error message I see above:

'IMvcCoreBuilder' does not contain a definition for 'AddJsonFormatters' and no accessible extension method 'AddJsonFormatters' accepting a first argument of type 'IMVCoreBuilder' could be found (are you using a missing directive or an assembly reference?)

Is this the method? Should I send an MVCCoreBuilder? How do I do that? MvcJsonMvcCoreBuilderExtensions.AddJsonFormatters Method

like image 479
mvojwe Avatar asked May 29 '19 16:05

mvojwe


1 Answers

When you call services.AddMvc() you get an IMvcBuilder.

if you want to add more output or input formatters, the IMvcBuilder has an extension method that you can call AddMvcOptions bellow you have an example of an XmlDataContractSerializerOutputFormatter that was added

    mvcBuilder.AddMvcOptions(options =>
        {
            options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
            options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter(options));

Mvc already has a JsonOutputFormatter ,so inside of the AddMvcOptions you can get it and also and add your own custom mediatypes if you need it.

var jsonOutputFormatter = options.OutputFormatters.OfType<JsonOutputFormatter>().FirstOrDefault();

        if (jsonOutputFormatter != null)
        {
            jsonOutputFormatter.SupportedMediaTypes.Add(HttpMediaTypes.Vnd+json.all);
            jsonOutputFormatter.SupportedMediaTypes.Add(HttpMediaTypes.ApplicationOctetStream);
        }
like image 61
Zinov Avatar answered Oct 05 '22 23:10

Zinov