简体   繁体   中英

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

I am new in programming. I read a tutorial about the .net core API, but I noticed every tutorial only shows how to pass an entity class as parameter. If I want to pass a combination of entity class as below, does it mean I need to submit multiple post request to server?

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; } 
 }

You need to change your object like above and then you need to return type List<Post>

You can create a viewModel to parse you json to an object as well. like this.

   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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM