我需要使用 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 和本网站上的其他方法一起使用。 可以帮忙吗?
使用您当前的代码:
[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);
....
}