简体   繁体   English

ASP.NET 核心 .NET 6 app 默认返回 XML 而不是 JSON

[英]ASP.NET Core .NET 6 app returning XML instead of JSON by default

We are migrating a .NET 2.2 app to .NET 6, and we are facing a problem where some third-party apps that make requests to our system without specifying the Accept HTTP header were getting back JSON data by default in .NET 2.2, but now they are getting XML when nothing is specified.我们正在将 .NET 2.2 应用程序迁移到 .NET 6,我们面临一个问题,即某些向我们的系统发出请求但未指定Accept HTTP header 的第三方应用程序正在取回 JSON 数据,但默认情况下它们现在是 8526208 中的 8524208未指定任何内容时获取 XML。

If I run the same request, but specify Accept as application/json , I get back JSON.如果我运行相同的请求,但将Accept指定为application/json ,我会返回 JSON。

Our app returns 99% of the results in JSON, but has a specific SOAP endpoint that returns XML (it communicates with another SOAP web service and returns SOAP on this single endpoint).我们的应用程序在 JSON 中返回了 99% 的结果,但有一个特定的 SOAP 端点返回 XML(它与另一个 SOAP web 服务通信,并在这个单一端点上返回 SOAP)。

The config is:配置是:

services.AddSoapCore();

services
    .AddMvc()
    .AddXmlSerializerFormatters()
    .AddNewtonsoftJson(options => options.SerializerSettings.Converters.Add(new StringEnumConverter()));

If I remove AddXmlSerializerFormatters() , the endpoint returns JSON correctly but then the SOAP endpoint stops working.如果我删除AddXmlSerializerFormatters() ,端点会正确返回 JSON 但随后 SOAP 端点会停止工作。

I am aware I can use the [Produces] attribute, but ideally we would keep the same default behavior instead of having to manually go through all endpoints.我知道我可以使用[Produces]属性,但理想情况下,我们会保持相同的默认行为,而不必通过所有端点手动 go。

Is there a way to configure the app to return JSON by default when nothing is specified, without removing XML support?有没有办法将应用程序配置为在未指定任何内容时默认返回 JSON,而不删除 XML 支持?

Asp.NET Core chooses registered formatters by their precedence and the order they added will be their precedence. Asp.NET Core 根据优先级选择已注册的格式化程序,并且它们添加的顺序将是它们的优先级。 So as you added XML formatter first, when no Accept header is appeared in request the first matched formatter will be XML formatter.因此,当您首先添加 XML 格式化程序时,当请求中没有出现 Accept header 时,第一个匹配的格式化程序将是 XML 格式化程序。 Just add JSON formatter first.只需先添加 JSON 格式化程序即可。

I reproduced the issue and adding JSON formatter first, successfully fixed the problem我重现了这个问题并先添加了 JSON 格式化程序,成功解决了问题

builder.Services
  .AddMvc()
  .AddNewtonsoftJson(options => options.SerializerSettings.Converters.Add(new StringEnumConverter()))
  .AddXmlSerializerFormatters();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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