【问题标题】:How to post list of object in ASP.NET Core Web API如何在 ASP.NET Core Web API 中发布对象列表
【发布时间】:2019-08-06 02:40:39
【问题描述】:

我看过一些教程,其中使用 POST 方法发送 json 对象。

[HttpPost]
public async Task<IActionResult> createEntity([FromBody]Entity entity)
{
    try
    {
         await _repository.Entity.CreateEntityAsync(entity);
         return Ok();
     }
     catch (Exception ex)
     {
          return StatusCode(500, "Internal server error");
      }
}

这可以正确地完成工作

现在如果我想发送:

{ “身份证”:1, “数据”:[ { “值1”:“xxxx”, “价值2”:“年年” }, { "value1":"zzzz", “价值 2”:“万维网” } ] }

如果你能推荐我做这个的最佳选择是什么

【问题讨论】:

    标签: c# asp.net-web-api .net-core entity-framework-core


    【解决方案1】:

    如下创建一个 DTO 类:

    public class YourDto
    {
       public int ID {get; set;}
       public List<Data> Data {get; set;}
    }
    

    其中Data如下:

    public class Data
    {
       public string Value1 {get; set;}
       public string Value2 {get; set;}
    }
    

    然后在你的 POST 方法中:

    [HttpPost]
    public async Task<IActionResult> createEntity([FromBody]YourDto yourDto)
    {
        try
        {
             // do whatever you want to do with the yourDto object
    
             return Ok();
        }
        catch (Exception ex)
        {
              return StatusCode(500, "Internal server error");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 2020-12-03
      • 2020-12-05
      • 2019-01-29
      相关资源
      最近更新 更多