【问题标题】:Processing a POST with a list of JSON in .NET Core API在 .NET Core API 中处理带有 JSON 列表的 POST
【发布时间】:2020-02-11 06:47:52
【问题描述】:

我正在尝试从表单中捕获用户响应 我的响应模型如下所示:

{
        public int UserId { get; set; }
        public int QId { get; set; }
        public int OptionId { get; set; }
        public string Response { get; set; }

        public SurveyCreatorOptions SurveyCreatorOptions { get; set; }
        public SurveyUserMasters User { get; set; }
    }

上述模型和创建的 DbContext 是使用 efcore 数据库优先方法在现有数据库的脚手架上创建的。

控制器中的 POST 方法如下所示:

// POST: api/SurveyUserResponses
        [HttpPost]
        public async Task<IActionResult> PostSurveyUserResponse([FromBody] SurveyUserResponse surveyUserResponse)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            _context.SurveyUserResponse.Add(surveyUserResponse);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (SurveyUserResponseExists(surveyUserResponse.UserId))
                {
                    return new StatusCodeResult(StatusCodes.Status409Conflict);
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtAction("GetSurveyUserResponse", new { id = surveyUserResponse.UserId }, surveyUserResponse);
        }





在我的控制器中使用此方法,我可以发送以下格式的发布请求:

{
        "userId": 1,
        "qId": 2,
        "optionId": 1,
        "response": "Male",
        "surveyCreatorOptions": null,
        "user": null
    }

上述方法将只捕获表单的一个字段,但我的表单包含多个字段。 所以我想发送一个这种格式的JSON

[
{
        "userId": 1,
        "qId": 1,
        "optionId": 1,
        "response": "XYZ",
        "surveyCreatorOptions": null,
        "user": null
    },

{
        "userId": 1,
        "qId": 2,
        "optionId": 1,
        "response": "Male",
        "surveyCreatorOptions": null,
        "user": null
    },

{
        "userId": 1,
        "qId": 3,
        "optionId": 4,
        "response": "Samsung",
        "surveyCreatorOptions": null,
        "user": null
    }
]

我是 .NET 新手,我对如何编写 POST 方法以及如何将上述列表中的每个元素绑定到我的数据库感到困惑。 我已经制作了 Ajax post 方法,它可以发送上述格式的 json,所以这不是问题

【问题讨论】:

    标签: json api asp.net-core post .net-core


    【解决方案1】:

    上述方法只会捕获表单的一个字段,但我的表单包含多个字段

    如果您将操作更改为接受List&lt;&gt;,内置的 ModeBinders 会注意:

    公共异步任务 PostSurveyUserResponse([FromBody] SurveyUserResponsesurveyUserResponse) 公共异步任务 PostSurveyUserResponse([FromBody] ListsurveyUserResponses) { …… }

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 2018-01-24
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    相关资源
    最近更新 更多