我正在尝试设置我的API,因此它会根据接受标头的XML或JSON响应。
我正在关注Shawn W:https://wildermuth.com/2016/03/16/content_negotiation_in_in_ asp_net_core
它说要添加一个软件包到: "Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-rc1-final"
,但我找不到它,而是安装了: Microsoft.AspNetCore.Mvc.Formatters.Xml
他说要将其添加到启动中的"配置服务"部分:
// Add framework services.
services
.AddMvc(options => {
options.RespectBrowserAcceptHeader = true;
options.InputFormatters.Add(new XmlSerializerInputFormatter());
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
}).AddJsonOptions(options => {
// Force Camel Case to JSON
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
然后自动打算接收XML,因为默认情况下它使用的是:text/xml标头,我不会在浏览器中或使用Postman中获得XML。无论我设置什么接受标题,我都会得到JSON。
我尝试将[Produces("application/xml")]
放在控制器上,并返回一个空白的OK页面。
默认情况下,我如何让我的API返回JSON,或者如果存在接受?
编辑1:
我正在将其作为http获取代码:
[HttpGet]
public IActionResult Get() {
var invoices = context.Invoices.ToList();
var mappedInvoices = mapper.Map<List<DomainModels.Invoice>, List<Invoice>>(invoices);
return Ok(mappedInvoices);
}
我正在尝试返回此DTO:
public class Invoice : TrackedObject {
public DateTime Date { get; set; }
public decimal Total { get; set; }
public string OrderNumber { get; set; }
public PaymentType? PaymentType { get; set; }
public ICollection<InvoiceItem> Items { get; set; }
}
public enum PaymentType {
Cheque,
Cash,
Card,
Account
}
编辑2:
如果我交换了这个:
// Add framework services.
services
.AddMvc(options => {
options.RespectBrowserAcceptHeader = true;
options.InputFormatters.Add(new XmlSerializerInputFormatter());
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
}).AddJsonOptions(options => {
// Force Camel Case to JSON
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
并替换为以下内容:
services.AddMvc().AddXmlSerializerFormatters();
然后将[Produces("application/xml")]
放在我的Get方法上方,我得到406不可接受的响应。
我终于找到了正确的设置,可以通过接受标头返回JSON和XML。
要让您的Web API控制器返回JSON或XML(默认情况下)您需要服务配置才能如下:
// Add framework services.
services
.AddMvc(options => {
options.RespectBrowserAcceptHeader = true;
})
//support application/xml
.AddXmlDataContractSerializerFormatters()
//support application/json
.AddJsonOptions(options => {
// Force Camel Case to JSON
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
当您知道如何时,很简单!当时有太多错误的文档!