【发布时间】:2016-07-11 21:16:59
【问题描述】:
我有以下简单的 Web API 控制器:
// 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 数据。
我在某处读到,为了获取 XML,我必须将 [DataContract] 和 [DataMember] 属性添加到我的 DTO,现在看起来像这样:
[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; }
}
我已经使用了几个小时了,但我只是不明白为什么它不起作用。我试过了:
-
使action方法同步和异步
-
直接返回数据,并设置返回类型为
IEnumerable<CustomerDto> -
将集合转换为数组而不是列表
-
返回
IActionResult -
返回单个项目,而不是集合
-
我已通过在调试器中检查 Accept 标头来验证它是否显示在请求中。
-
大量“使用 Bing 搜索”并阅读各种博客
-
从模板创建一个新的 WebAPI 项目,看看那里是否有任何灵感(不是真的)。
我希望它很简单,但我看不到它......
【问题讨论】:
-
你能证明你在 Startup.cs 中注册了你的 Xml 格式化程序吗?
-
你配置过格式化程序吗?
-
这当然是问题所在。上次我使用了默认启用的 WebAPI。我忘记了 ASP.Net 5 中新的轻量级现收现付方法!不过,扩展方法也不是很容易被发现。我必须知道安装另一个 NuGet 包,然后点到 AddMvc() 调用中。
标签: xml asp.net-web-api asp.net-core asp.net-core-mvc