ASPNetCore API内容协商不起作用

时间:2017-03-07 16:44:04

标签: xml asp.net-web-api asp.net-core content-negotiation http-accept-header

我试图设置api,以便根据Accept标头响应XML或JSON。

我按照Shawn W的教程:https://wildermuth.com/2016/03/16/Content_Negotiation_in_ASP_NET_Core

它说要将包添加到: 1 : Alter table_name add columns flag integer /* table_name row count 10000*/ 2 :update table_name set flag = 1 where/* some condition*/ -----rows affected 4000 3.update table_name set flag = 0 where flag<> 1 ----rows affected 0

但我无法找到它而是安装: "Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-rc1-final"

他说要将它添加到Startup中的配置服务部分:

Microsoft.AspNetCore.Mvc.Formatters.Xml

然后浏览器自动接收XML,因为默认情况下它使用Accept:text / xml标头,我不会在浏览器中使用XML或使用邮递员。无论我把Accept头设置为什么,我都会得到Json。

我已经尝试将 // 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(); }); 放在我的控制器上,它会返回一个空白的200 OK页面。

如何默认返回我的api,如果存在Accept,则返回XML?

修改1:

我使用它作为我的http获取代码:

[Produces("application/xml")]

我试图归还这个DTO:

    [HttpGet]
    public IActionResult Get() {
        var invoices = context.Invoices.ToList();
        var mappedInvoices = mapper.Map<List<DomainModels.Invoice>, List<Invoice>>(invoices);
        return Ok(mappedInvoices);
    }

编辑2:

如果我换掉这个:

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
}

并替换为以下内容:

 // 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(); 放在我的get方法之上,我得到406 Not Acceptable response。

1 个答案:

答案 0 :(得分:10)

我终于找到了通过接受标头返回JSON和XML的正确设置。

要让您的Web API控制器返回JSON或XML(默认为JSON),您需要将服务配置看起来像这样:

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

当你知道如何时非常简单!在那一刻,有太多不正确的文件存在!