简体   繁体   English

ASPNetCore API内容协商不起作用

[英]ASPNetCore API Content negotiation not working

I'm trying to get my api set up so it will respond with with XML or JSON depending upon the Accept header. 我正在尝试设置我的api,以便根据Accept标头响应XML或JSON。

I'm following the tutorial by Shawn W: https://wildermuth.com/2016/03/16/Content_Negotiation_in_ASP_NET_Core 我正在关注Shawn W的教程: https//wildermuth.com/2016/03/16/Content_Negotiation_in_ASP_NET_Core

It says to add a package to: "Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-rc1-final" 它说要添加一个包: "Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-rc1-final"

But I couldn't find it so instead installed: Microsoft.AspNetCore.Mvc.Formatters.Xml 但我无法找到它而是安装: Microsoft.AspNetCore.Mvc.Formatters.Xml

He says to add this to the config services section in Startup: 他说要将它添加到Startup中的配置服务部分:

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

Then the browser is automatically meant to receive XML because by default it uses Accept: text/xml header, I don't get XML in my browser or by using postman. 然后浏览器自动接收XML,因为默认情况下它使用Accept:text / xml标头,我不在浏览器中使用XML或使用邮递员。 I get Json no matter what I set Accept header to. 无论我将Accept头设置为什么,我都会得到Json。

I've tried putting [Produces("application/xml")] on my controller and it returns a blank 200 OK page. 我已经尝试将[Produces("application/xml")]放在我的控制器上,它返回一个空白的200 OK页面。

How do I get my api to return Json by default, or XML if Accept is present? 如何让我的api默认返回Json,如果存在Accept,则返回XML?

Edit 1: 编辑1:

I'm using this as my http get code: 我正在使用它作为我的http获取代码:

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

And I'm trying to return this DTO: 而我正试图归还这个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
}

Edit 2: 编辑2:

If I swap out this: 如果我换掉这个:

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

and replace with the below: 并替换为以下:

        services.AddMvc().AddXmlSerializerFormatters();

And then put [Produces("application/xml")] above my get method I get a 406 Not Acceptable response. 然后将[Produces("application/xml")]放在我的get方法之上,我得到406 Not Acceptable响应。

I finally found the correct setup to return JSON and XML via accept headers. 我终于找到了正确的设置,通过accept头返回JSON和XML。

To get your web API controllers to return JSON or XML (JSON by default) you need your services configuration to look like this: 要使您的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();
    });

Pretty simple when you know how! 当你知道如何时非常简单! There is so much incorrect documentation laying around at the minute! 一分钟都有不正确的文档!

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

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