繁体   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