【问题标题】:.Net Core 1.1 Web API Json Input/Output formatters.Net Core 1.1 Web API Json 输入/输出格式化程序
【发布时间】:2017-09-11 15:55:57
【问题描述】:

我正在构建一个 Web API,我可以在其中在启动类中添加输入/输出格式化程序。这适用于 XML,但不适用于 Json。我知道默认情况下会添加 Json,但如果未指定 Accept 标头,它似乎会选择 XML。

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>();
}

在配置服务方法中,我添加了 xmlSerializer,但这不适用于 Json:

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

默认格式化程序是添加到格式化程序列表中的第一个。我想在 XML 之前添加 Json 格式化程序,这样它将成为默认值。我错过了什么?如何正确添加 Json 格式化程序,使其在格式化程序列表中排在首位?

【问题讨论】:

    标签: c# asp.net-core-webapi asp.net-core-1.1


    【解决方案1】:

    我假设请求的 Accept 标头设置为 XML 而不是 JSON。仅当请求的 Accept 头指定格式时才进行协商,否则使用默认值(默认为 JSON),如果不能满足请求,则由服务器决定。

    如果您一直在获取 XML,我猜是消费者的请求是在请求 XML。

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多