简体   繁体   English

如何在.NET Core API中将多个实体或json作为参数传递

[英]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. 我阅读了有关.net核心API的教程,但我注意到每一篇教程都仅展示了如何将实体类作为参数传递。 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: JSON:

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

C#: 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> 您需要像上面一样更改对象,然后需要返回类型List<Post>

You can create a viewModel to parse you json to an object as well. 您可以创建一个viewModel来将json也解析为一个对象。 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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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