簡體   English   中英

如何在.NET Core API中將多個實體或json作為參數傳遞

[英]How to pass multiple entity or json as parameter in .net core api

我是編程新手。 我閱讀了有關.net核心API的教程,但我注意到每一篇教程都僅展示了如何將實體類作為參數傳遞。 如果我想通過以下實體類的組合,是否意味着我需要向服務器提交多個發布請求?

JSON:

{
"postId": "123",
"postText": "test item", 
"items": [
    {
        "itemId": "t3st", 
        "postId": null
    },
    {
        "itemId": "t3st3", 
        "postId": null
    }
] }

C#:

public class Post
{
    [Key]
    public string postId { get; set; }
    public string postText { get; set; }
}

public class Item
{
    [Key]
    public string itemid{ get; set; }
    public string postId { get; set; } 
 }

public IActionResult Post([FromBody] Post post)
{
    return Ok(data);
}
public class Post
{
    [Key]
    public string postId { get; set; }
    public string postText { get; set; }
    public List<Item> items {get; set;}

}

public class Item
{
    [Key]
    public string itemid{ get; set; }
    public string postId { get; set; } 
 }

您需要像上面一樣更改對象,然后需要返回類型List<Post>

您可以創建一個viewModel來將json也解析為一個對象。 像這樣。

   public class Post
{
    [Key]
    public string postId { get; set; }
    public string postText { get; set; }
    public IEnumerable<Item> items {get; set;}

}

public class Item
{
    [Key]
    public string itemid{ get; set; }
    public string postId { get; set; } 
 }

public IActionResult Post([FromBody] Post post)
    {
        var entity = JsonConvert.DeserializeObject<PostViewModel>(post.ToString())
        return Ok(data);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM