Web API C# 模型

问题描述 投票:0回答:1

如何创建一个在 API POST 中接受此信息的模型?

{
    "formId": "ff2f0a7f-aa26-11ee-bc5f-0242ac110009",
    "workflowId": "",
    "status": "Draft",
    "formData": {
        "input[f521099a-ae5b-11ee-bc5f-0242ac110009]": "0bd946d0-ae5c-11ee-bc5f-0242ac110009, b022e9f9-ae78-11ee-bc5f-0242ac110009",
        "input[df8dd2e4-ae66-11ee-bc5f-0242ac110009][e46ce484-ae66-11ee-bc5f-0242ac110009]": "e46ce484-ae66-11ee-bc5f-0242ac110009",
        "input[df8dd2e4-ae66-11ee-bc5f-0242ac110009][e81189ee-ae66-11ee-bc5f-0242ac110009]": "e81189ee-ae66-11ee-bc5f-0242ac110009",
        "input[d0cd94fe-ae78-11ee-bc5f-0242ac110009]": "asdasd"
    }
}

我试过这个:

public record ContentFormAnswerDto(
    [Required, MinLength(36), MaxLength(40)] string FormId,
    [MinLength(36), MaxLength(40)] string? WorkflowId = null,
    string? Status = null,
    string? FormData = null
);

[HttpPost]
[Produces("application/json")]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
[ProducesResponseType(typeof(MessageHandlerRm), 201)]
public IActionResult Create([FromBody] ContentFormAnswerDto dto)

我得到:

{
  "errors": {
    "dto": [
      "The dto field is required."
    ],
    "formData": [
      "Unexpected character encountered while parsing value: {. Path 'formData', line 5, position 15."
    ]
  },
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-d80738856fa30bc66e1f7c37838ab707-6e11c03c42b4b6b8-00"
}
c# json asp.net-core model asp.net-core-webapi
1个回答
0
投票

好的决定采用其他方法

{
    "formId": "ff2f0a7f-aa26-11ee-bc5f-0242ac110009",
    "workflowId": null,
    "status": "Draft",
    "formData": [
        {
            "questionId": "f521099a-ae5b-11ee-bc5f-0242ac110009",
            "answer": [
                "0bd946d0-ae5c-11ee-bc5f-0242ac110009",
                "b022e9f9-ae78-11ee-bc5f-0242ac110009"
            ]
        },
        {
            "questionId": "f521099a-ae5b-11ee-bc5f-0242ac110009",
            "answer": [
                "asdasd"
            ]
        }
    ]
}

DTO

/// <summary>
/// ContentFormAnswer Dto
/// </summary>
/// <param name="FormId"></param>
/// <param name="WorkflowId"></param>
/// <param name="Status"></param>
/// <param name="FormData"></param>
public record ContentFormAnswerDto(
    [Required, MinLength(36), MaxLength(40)] string FormId,
    [MinLength(36), MaxLength(40)] string? WorkflowId = null,
    string? Status = null,
    Input[]? FormData = null
);

/// <summary>
/// Input Dto
/// </summary>
/// <param name="QuestionId"></param>
/// <param name="Answer"></param>
public record Input(
    string QuestionId,
    string[] Answer
);
© www.soinside.com 2019 - 2024. All rights reserved.