我正在嘗試通過我制作的另一個 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陣列及其物件。
有什么我做錯了嗎?為什么它回傳一個空陣列?在此先感謝您的幫助..
uj5u.com熱心網友回復:
正如我在評論中提到的,你需要改變的Entries財產BasketDTO,以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>();
}
uj5u.com熱心網友回復:
好吧,當有 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();
您不應該 return IEnumerable,而應該回傳 list (或陣列)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/403894.html
標籤:
