【发布时间】: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