我试图通过我制作的另一个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
}
]
}
其中我想要得到CCD_ 3数组及其对象。
我做错什么了吗?为什么它返回一个空数组?提前感谢您的帮助。。
正如我在评论中提到的,您需要将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>();
}
当有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
,而应该返回列表(或数组(。