【发布时间】: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