为什么我的ASP.Net Core Web API控制器不返回XML? [英] Why won't my ASP.Net Core Web API Controller return XML?

查看:606
本文介绍了为什么我的ASP.Net Core Web API控制器不返回XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的Web API控制器:

I have the following simple Web API controller:

    // GET: api/customers
    [HttpGet]
    public async Task<IActionResult> Get()
        {
        var customers = await uow.Users.GetAllAsync();
        var dto = customers.Select(p => new CustomerDto {Id = p.Id, Email = p.Email, UserName = p.UserName});
        return Ok(dto); // IEnumerable<CustomerDto>
        }

在邮递员中,我将Accept标头设置为application/xml,但是无论我如何尝试,我都只能取回JSON数据.

In Postman, I'm setting the Accept header to application/xml, but no matter what I try, I can only get JSON data back.

我在某处读到要获取XML,必须在我的DTO中添加[DataContract][DataMember]属性,现在看起来像这样:

I read somewhere that in order to get XML, I must add [DataContract] and [DataMember] attributes to my DTO, which now looks like this:

[DataContract]
public class CustomerDto
    {
    [DataMember]
    public string Id { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    [DataMember]
    public string Email { get; set; }

    [Required]
    [Display(Name = "Login Name")]
    [DataMember]
    public string UserName { get; set; }
    }

我已经花了几个小时了,我只是不明白为什么它不起作用.我尝试过:

I've been at it several hours now and I'm just not seeing why it doesn't work. I've tried:

  • 使动作方法同步和异步

  • Making the action method synchronous and asynchronous

直接返回数据,并将返回类型设置为IEnumerable<CustomerDto>

Returning the data directly, and setting the return type to IEnumerable<CustomerDto>

将集合转换为数组而不是列表

Converting the collection to an array instead of a list

返回IActionResult

返回单个项目,而不是集合

Returning a single item, instead of a collection

我已通过在调试器中对其进行检查,验证了Accept标头已显示在请求中.

I've verified that the Accept header is showing up in the request by examining it in the debugger.

很多与Bing谷歌搜索"并阅读各种博客

Lots of "Googling with Bing" and reading various blogs

从模板创建一个新的WebAPI项目,并查看那里是否有任何灵感(不是真的).​​

Creating a new WebAPI project from the template and seeing if there is any inspiration there (not really).

我希望它很简单,但是我看不到...

I expect it's simple, but I can't see it...

推荐答案

Xml格式程序是单独程序包的一部分:Microsoft.AspNetCore.Mvc.Formatters.Xml

Xml formatters are part of a separate package: Microsoft.AspNetCore.Mvc.Formatters.Xml

添加以上程序包并更新您的startup.cs,如下所示:

Add the above package and update your startup.cs like below:

services
    .AddMvc()
    .AddXmlDataContractSerializerFormatters();

OR

services
    .AddMvc()
    .AddXmlSerializerFormatters();

这篇关于为什么我的ASP.Net Core Web API控制器不返回XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆