reactjs 找不到向.NET后端API发送axios post请求的正确方法(FromBody)

50pmv0ei  于 2023-05-06  发布在  React
关注(0)|答案(1)|浏览(114)

你好,我正在尝试向以下端点发送post请求:

[HttpPost]
    [Route("/admin/plebs/decision")]
    public async Task<IActionResult> CreatePlebsDecisions(
        [FromBody] IEnumerable<CreatePlebsDecisionsRequest> decisionsRequest)

“CreatePlebsDecisionsRequest”看起来如下:

public record CreatePlebsDecisionsRequest
{
    public required string AdminId { get; set; }
    public required string PlebId { get; init; }
    public required bool IsAccepted { get; init; }
}

但是,当我发送这样的请求(通过Axios)时

// types
export type PlebsDecisionsRequests = {
  decisionsRequest: PlebDecision[];
};

export type PlebDecision = {
  plebId: string;
  isAccepted: boolean;
};
// calling code in component
const plebsDecisions = plebRequests.map((pr) => ({
      plebId: pr.plebId,
      isAccepted: pr.isAccepted,
    }));

    const request = {
      decisionsRequest: plebsDecisions,
    };
// the method itself
await makePlebsDecisions(request);
  const makePlebsDecisions = async (
    plebsDecisions: PlebsDecisionsRequests
  ): Promise<PlebRequestResponse> => {
    setIsLoading(true);

    const payload = JSON.stringify(plebsDecisions);

    try {
      const response = await axios.post('/admin/plebs/decision', payload);
// the post object in chome dev tools
{
    "decisionsRequest": [
        {
            "plebId": "8e694149-102c-4d23-9e43-3555b46b4c4b",
            "isAccepted": true
        }
    ]
}

我得到以下错误消息(来自API):

{
    "$": [
        "The JSON value could not be converted to System.Collections.Generic.IEnumerable`1[DalaranApp.Contracts.Admins.Decisions.CreatePlebsDecisionsRequest]. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
    ],
    "decisionsRequest": [
        "The decisionsRequest field is required."
    ]
}

我似乎找不到解决办法,有什么想法吗?
先谢谢你了

bxjv4tth

bxjv4tth1#

我终于找到了解决方案,它看起来如下:
请求对象应更改为:

public record CreatePlebsDecisionsRequest
{
    public string? AdminId { get; set; }
    public string PlebId { get; init; }
    public bool IsAccepted { get; init; }
}

这是游戏规则改变者:控制器应该接受LIST而不是IENUMERABLE(我不知道为什么IEnumerable不起作用)

[HttpPost]
[Route("/admin/plebs/decision")]
public async Task<IActionResult> CreatePlebsDecisions(
    [FromBody] List<CreatePlebsDecisionsRequest> decisionsRequest)

做了那些改动之后,一切都正常了

相关问题