如何在 Blazor 中将 PostAsJsonAsync 与包含数组的字段一起使用?

How to use PostAsJsonAsync with fields containing arrays in Blazor?

@inject HttpClient Http 
@page "/"
<button class="checkout" @onclick="() => createOrder()">Place Order</button>
@code {

public List<CartToSendItems> items { get; set; } = new List<CartToSendItems>();
public class CartToSend
{
    public Guid customerId { get; set; }
    public List<CartToSendItems> items = new List<CartToSendItems>();
}
public class CartToSendItems
{
    public int productId { get; set; }
    public int qty { get; set; }
}
public async Task createOrder()
{
    CartToSend body = new CartToSend();
    body.customerId = Guid.Parse("68e03745-e4a2-480f-9f39-eac36aa1ddcd");
    body.items = GetItems();
    var jsonBody = System.Text.Json.JsonSerializer.Serialize<CartToSend>(body);
    Console.WriteLine(jsonBody.ToString());
    Console.WriteLine("items: " + body.items.Count.ToString());
    var httpResponse = await Http.PostAsJsonAsync<CartToSend>("http://localhost:1337/orders/create", body);
}
protected List<CartToSendItems> GetItems() {
    List<CartToSendItems> ret = new List<CartToSendItems>();
    CartToSendItems item1 = new CartToSendItems();
    item1.productId = 1;
    item1.qty = 2;
    CartToSendItems item2 = new CartToSendItems();
    item2.productId = 4;
    item2.qty = 2;
    ret.Add(item1);
    ret.Add(item2);
    return ret;
}
} 

这实际上只是发送了 customerId 并且项目被忽略了。所以后端服务器只是接收:{ customerId: '68e03745-e4a2-480f-9f39-eac36aa1ddcd' }

执行此操作的正确方法是什么?提前致谢

编辑:为了更好地理解原始示例而编辑的示例。

我的控制台输出:

{"customerId":"68e03745-e4a2-480f-9f39-eac36aa1ddcd"}

项目:2

NodeJS 后端日志:

侦听 ws://127.0.0.1:5858/1c18c737-e806-4770-ac13-8bd6e6c821b3 的调试器

如需帮助,请参阅:https://nodejs.org/en/docs/inspector

已附加调试器。

获取 / 304 466.248 毫秒 - -

获取 /stylesheets/main.css 304 1.439 毫秒 - -

选项 /orders/create 204 0.463 毫秒 - 0

缺少字段 { customerId: '68e03745-e4a2-480f-9f39-eac36aa1ddcd' }

POST /orders/create 403 18.247 毫秒 - 18

我确定这是您的 class CartToSend 将列表描述为一个字段而不是 属性 的问题,因此它没有被序列化。

改变

public List<CartToSendItems> items = new List<CartToSendItems>();

public List<CartToSendItems> items {get;set;} = new List<CartToSendItems>();

替换此方法:

public class CartToSend
{
    public Guid customerId { get; set; }
    public List<CartToSendItems> items = new List<CartToSendItems>();
}

作者:

public class CartToSend
        {
            public Guid customerId { get; set; }
            public List<CartToSendItems> items { get; set; } = new List<CartToSendItems>();
        }

'items' 被声明为未序列化的字段