简体   繁体   中英

.Net Core 1.1 Web API Json Input/Output formatters

I am building a Web API in which I can add input/outut formatters in the start up class. This works for XML but its not working for Json. I know Json is added by default but it seems to choose XML if the Accept header is not specified.

public void ConfigureServices(IServiceCollection services)
{
   //Add framework services.
   services.AddMvc(options =>
   {
       options.RequireHttpsPermanent = true;
       options.RespectBrowserAcceptHeader = true;
       options.ReturnHttpNotAcceptable = true;
       options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
       options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter());
     });

    services.AddDbContext<CustomerManagerContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
    );

    services.AddScoped<IUnitOfWork, UnitOfWork>();
}

In the configure services method I added the xmlSerializer however this does not work for Json:

options.OutputFormatters.Add(new JsonOutputFormatter());

The default formatter is the first one added to the list of formatters. I would like to add the Json formatters before the XML so it would become the default. What am I missing? How do I properly add the Json formatter so it is first in the list of formatters?

I'm assuming the Accept header of the request is set for XML instead of JSON. Negotiations are only done if the Accept header of the request specifies a format, otherwise the default is used (JSON by default), and if that can't meet the request, the server decides.

If you're getting XML all the time, my guess is the request from the consumer is asking for XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM