使用 IHttpClientFactory 向 API 发送 POST 请求

问题描述 投票: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": "One or more validation errors occurred.",
    "status": 400,
    "errors": {
        "name": ["The name field is required."],
        "districtname": ["The districtname field is required."]
    },
    "traceId": "00-d8380633c81cdd4c0a7560cceff50c7a-0482c70fcbcf252f-00"
}

我知道这是语义,但我看不到它。我在 .Net Core 8 中工作。我想了解该错误,我已经尝试使其与

HttpClient
和本网站上的其他方法一起使用。 你能帮忙吗?

c# json asp.net-core-webapi http-post dotnet-httpclient
1个回答
1
投票

使用您当前的代码:

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

该操作期望接收

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

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

using System.ComponentModel.DataAnnotations;

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);

    ....
}

或者,您可以通过

PostAsJsonAsync
发布 JSON 正文。

对于 .NET Framework:Microsoft.AspNet.WebApi.Client(包) 对于 .NET 8:System.Net.Http.Json(命名空间)

using var httpResponse = await httpClient.PostAsJsonAsync(localHost, person);
© www.soinside.com 2019 - 2024. All rights reserved.