【问题标题】:API Returns OK in API but no DataAPI 在 API 中返回 OK 但没有数据
【发布时间】:2022-01-04 19:55:26
【问题描述】:

我正在尝试通过我制作的另一个 API 返回模型中的对象,但是当我在 PostMan 上使用 GET 获取我的 API 时,它只返回 200 OK 但一个空数组。

这就是我想要得到的:

[
  {
    "productId": 0,
    "quantity": 0
  }
]

这就是我在 PostMan 中得到的内容

[]

通过使用此 API URL 调用:

http://localhost:5700/api/Orders/basket/firstId

这是我的控制器和我在 Postman 中调用的相应 GET 方法:

[HttpGet("basket/{identifier}")]
public async Task<IEnumerable<BasketEntryDto>> FetchBasketEntries(string identifier)
{
    var httpRequestMessage = new HttpRequestMessage(
       HttpMethod.Get,
       $"https://localhost:5500/api/Basket/{identifier}")
    {
        Headers = { { HeaderNames.Accept, "application/json" }, }
    };

    var httpClient = httpClientFactory.CreateClient();

    using var httpResponseMessage =
        await httpClient.SendAsync(httpRequestMessage);

    var basketEntires = Enumerable.Empty<BasketEntryDto>();

    if (!httpResponseMessage.IsSuccessStatusCode)
        return basketEntires;

    using var contentStream =
        await httpResponseMessage.Content.ReadAsStreamAsync();

    var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };

    var basketDTO = await JsonSerializer.DeserializeAsync
            <BasketDto>(contentStream, options);

    //basketDTO = new NewBasketDTO.ItemDTO
    //{
    //    ProductId = basketDTO.ProductId,
    //    Quantity = basketDTO.Quantity
    //};

    basketEntires = basketDTO.Entries.Select(x =>
        new BasketEntryDto
        {
            ProductId = x.ProductId,
            Quantity = x.Quantity
        }
    );

    return basketEntires; // 200 OK
}

这是我的BasketDTO

public class BasketDto
{
    public string Identifier { get; set; }
    public IEnumerable<BasketEntryDto> Entries { get; set; } = new List<BasketEntryDto>();
}

还有我的BasketEntryDto

public class BasketEntryDto
{
    public int ProductId { get; set; }
    public int Quantity { get; set; }
}

这是 JSON 中的原始 API:

{
    "identifier": "mrPostMan",
    "items": [
        {
            "productId": 1,
            "quantity": 1
        }
    ]
}

我想在其中获取items 数组及其对象。

我做错了什么吗?为什么它返回一个空数组?提前感谢您的帮助..

【问题讨论】:

  • 您是否尝试过使用调试器检查状态?
  • 在 basketdto 中,您是否尝试将第二个属性命名为项目而不是条目?
  • @kks21199 是的,现在当我将其更改为项目时它工作了!谢谢!但为什么它不工作呢?
  • @NMNamuAgain 为什么会想到从 json 中取出 items 并将其放入 C# 中的 Entries 中?如果它决定接受用户输入并将其存储在您的随机变量中,您是否也会感激不尽?
  • @NMNamuAgain 很高兴它成功了。如果您仍想继续在BasketDTO 中使用Entries 属性,我已将其添加为答案以及您可以使用的另一个属性。

标签: c# entity-framework asp.net-core


【解决方案1】:

正如我在 cmets 中提到的,您需要将 BasketDTO 中的 Entries 属性更改为 Items 以匹配 JSON 属性名称。

public class BasketDto
{
    public string Identifier { get; set; }
    public IEnumerable<BasketEntryDto> Items { get; set; } = new List<BasketEntryDto>();
}

或者,您也可以使用JsonPropertyNameAttribute 明确提及 JSON 属性名称

public class BasketDto
{
    public string Identifier { get; set; }

    [JsonPropertyName("items")] 
    public IEnumerable<BasketEntryDto> Entries { get; set; } = new List<BasketEntryDto>();
}

【讨论】:

  • 非常感谢你,这成功了,我现在看到了我的错误,我对 .NET 了解不多 :) 但这很感激
【解决方案2】:

当有超过 0 个项目(篮子不是空的)时,这将起作用,但当篮子为空时则不行:

basketEntires = basketDTO.Entries.Select(x =>
        new BasketEntryDto
        {
            ProductId = x.ProductId,
            Quantity = x.Quantity
        }
    );

没有项目,选择将不起作用。所以你可以这样做:

if(basketEntires.Count == 0)
{
     basketEntires = new BasketEntryDto 
         { 
              ProductId = 0,
              Quantity  = 0 
         }
}

return basketEntires; // 200 OK

别忘了加.ToList():

basketEntires = basketDTO.Entries.Select(x =>
    new BasketEntryDto
    {
        ProductId = x.ProductId,
        Quantity = x.Quantity
    }
).ToList();

您不应返回IEnumerable,而应返回列表(或数组)。

【讨论】:

  • 感谢您的帮助!非常感谢您的帮助!虽然我刚刚将 BasketDTO 中 IEnumerable 的名称从 Entries 更改为 Items,但在 @kks21199 建议我这样做并且有效:D 无论如何感谢大家的帮助
  • @NMNamuAgain 非常欢迎你
猜你喜欢
  • 2020-07-15
  • 2021-10-29
  • 2020-02-22
  • 2022-11-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-17
  • 2015-04-26
  • 1970-01-01
相关资源
最近更新 更多