使用 IHTTPFactory 向 API 发送帖子

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

我需要使用 WPF 中的 API HTTPPost。我发出了这个命令:

     public async override void Execute(object? parameter)
     {
        string localHost = "https://localhost:7235/api/SalePerson/InsertSalePerson";
        var person = new DistrictAndSalePerson { name = _showDistrictViewModel.SalepersonToAdd, districtname = _showDistrictViewModel.SelectedDistrictTest };

        var httpClient = _httpClientFactory.CreateClient();
        var todoItemJson = new StringContent(JsonSerializer.Serialize(person),
        Encoding.UTF8,
        "application/json");
        using var httpResponse =
            await httpClient.PostAsync(localHost, todoItemJson);

        var response = await httpClient.PostAsync(localHost, todoItemJson);
        var result = await httpResponse.Content.ReadAsStringAsync();
        }

API 是:

[HttpPost("InsertSalePerson")]
[ProducesResponseType(  StatusCodes.Status200OK)]
public async Task<IActionResult> InsertSalePerson(
    [Required(AllowEmptyStrings = false)] string name,
    [Required(AllowEmptyStrings = false)] string districtname)
{

 try
    {
        await _districtRepo.InsertSalePerson(name, districtname);
        return Ok();
    }
    catch(Exception ex)
    {
        return BadRequest(ex);
    }

}

不幸的是,它总是返回验证错误:{“type”:“https://tools.ietf.org/html/rfc9110#section-15.5.1”,“title”:“发生一个或多个验证错误。”, "status":400,"errors":{"name":["名称字段为必填项。"],"districtname":["地区名称字段为必填项。"]},"traceId":"00-d8380633c81cdd4c0a7560cceff50c7a -0482c70fcbcf252f-00"}

我知道这是语义,但我无法真正看到它。我在 .Net Core 8 工作。我想了解该错误,我已经尝试使其与 httpclient 和本网站上的其他方法一起使用。 可以帮忙吗?

c# json asp.net-web-api http-post dotnet-httpclient
1个回答
0
投票

使用您当前的代码:

[HttpPost("InsertSalePerson")]
[ProducesResponseType(  StatusCodes.Status200OK)]
public async Task<IActionResult> InsertSalePerson(
    [Required(AllowEmptyStrings = false)] string name,
    [Required(AllowEmptyStrings = false)] string districtname)
{
    ...
}

该操作期望接收

name
districtname
作为查询字符串参数,但您将 JSON 对象作为请求正文发布。

您应该通过添加参数来创建模型类

public class InsertSalePerson
{
    [Required(AllowEmptyStrings = false)] 
    public string Name { get; set; }
    [Required(AllowEmptyStrings = false)]
    public string Districtname { get; set; }
}

并使用

[FromBody]
属性修改操作签名。

public async Task<IActionResult> InsertSalePerson([FromBody] InsertSalePersonModel model)
{

    ...

    await _districtRepo.InsertSalePerson(model.Name, model.Districtname);

    ....
}
© www.soinside.com 2019 - 2024. All rights reserved.