为什么我的 ASP.Net Core Web API 控制器不返回 XML? [英] Why won't my ASP.Net Core Web API Controller return 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>
}
在 Postman 中,我将 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,我必须将 [DataContract]
和 [DataMember]
属性添加到我的 DTO,现在看起来像这样:
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:
使action方法同步和异步
Making the action method synchronous and asynchronous
直接返回数据,并设置返回类型为IEnumerable
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();
或
services
.AddMvc()
.AddXmlSerializerFormatters();
这篇关于为什么我的 ASP.Net Core Web API 控制器不返回 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!