【问题标题】:How to append meta data to Web Api response如何将元数据附加到 Web Api 响应
【发布时间】:2017-08-24 17:18:52
【问题描述】:

请您在下面提供帮助。

  1. 我需要将 api 响应作为 IEnumerable 类型的 JSON 响应返回,以及我需要将我自己的 json 属性附加到此返回对象的响应。

    private async Task<IEnumerable<Funds>> GetFundDetails(int productid)
    {
        var action = $"productfunds/{productid}/detail";
        var res = await HttpClient.GetAsync($"{BaseResource}{action}");
        res.EnsureSuccessStatusCode();
        var collection = await res.Content.ReadAsAsync<Dto.FundDetail>();
        var items = (collection.Funds ?? Enumerable.Empty<Dto.Funds>()).Select<Dto.FundDetail, FundAsset>(MapFunds);
        return items;
    }
    

回复:

{
"items": [
    {
  "fundId": "036",
  "fundName": "ABC Fund",
  "amount": 1248111.26
},
{
  "fundId": "037",
  "fundName": "XYZ Fund",
  "amount": 7858564.84
}
]
}

预期响应:

{
  "items": [
    {
      "fundId": "036",
      "fundName": "ABC Fund",
      "amount": 1248111.26
    },
    {
      "fundId": "037",
      "fundName": "XYZ Fund",
      "amount": 7858564.84
    }
   ],
   ProductName: "PQR Product"
   ProductId: "1001"
}

-> 我需要从集合对象中附加 ProductName 和 ProductId,它们是 Dto.FundDetail 的属性。

【问题讨论】:

  • 您遇到了什么问题阻止了您提议的更改?
  • 如何通过附加产品名称和产品 ID 实现如上所示的预期响应
  • 您提议的更改不再是可枚举的,而是一种包含一些属性和 IEnumerable 的新型模型。维护 IEnumerable 结果的一种方法是将ProductNameProductId 添加到每个items
  • 或者改变调用者的期望,从响应中提取集合。

标签: .net asp.net-core asp.net-core-webapi


【解决方案1】:

您应该创建包含Dto.FundsProductIdProductName 的新模型, 像这样的东西:

   public class NewModelToReturn{

     public List<Dto.Funds> Funds{get;set;}
     public string ProductName;
     public string ProductId;

 }

顺便说一句,我还鼓励您阅读我的这篇关于设计 ASP.NET Web Api 响应的博客文章,以了解有关返回一致 Web Api 响应(包括成功和失败响应)的更多信息:https://www.vladopandzic.com/asp-net-web-api/building-consistent-responses-asp-net-web-api/

【讨论】:

    猜你喜欢
    • 2022-11-16
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2020-02-24
    • 2012-03-23
    相关资源
    最近更新 更多