You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 3.1 API不接收Postman POST请求体报验证错误如何解决

问题原因

  • CategoryDTO类的属性使用了私有set访问器:.NET Core 3.1默认使用的System.Text.Json序列化器不支持为私有set的属性赋值,请求体反序列化后Description和Observable属性均为null,直接触发Required验证规则。
  • 代码存在多处拼写错误:
    1. 接口方法的参数类型写为DTOs.CategotyDTO,正确类名应为CategoryDTO(拼写时遗漏了字母e)
    2. 实例化Category时调用的categoryDTO.Obervable属性名拼写错误,正确应为Observable(拼写时遗漏了字母s)
  • Postman请求的JSON末尾存在多余逗号,部分严格的JSON解析器会判定该格式非法。
  • 若未主动配置请求头,可能缺少Content-Type: application/json标识,导致服务端无法正确识别JSON格式的请求体。

解决方案

  1. 将CategoryDTO的属性set访问器改为public,这是最直接的修复方案:
public class CategoryDTO
{
    public Guid Id { get; set; }
    [Required(ErrorMessage = "Description is required", AllowEmptyStrings = false)]
    public string Description{ get; set; }
    [Required(ErrorMessage = "Observable is required", AllowEmptyStrings = false)]
    public string Observable{ get; set; }          
}

如果确实需要限制属性的外部修改权限,也可以在Startup.cs的ConfigureServices方法中配置System.Text.Json支持非公共访问器:

services.AddControllers()
    .AddJsonOptions(options =>
    {
        // 允许序列化/反序列化非公共成员
        options.JsonSerializerOptions.IncludeFields = true;
        // 保持属性名大小写匹配(可选,根据实际需求配置)
        options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
    });
  1. 修正所有拼写错误:
  • 将接口参数类型改为DTOs.CategoryDTO
  • 将代码中categoryDTO.Obervable改为categoryDTO.Observable
  1. 调整Postman请求配置:
  • 移除JSON末尾的多余逗号:
{
    "Description": "Category 1",
    "Observable": "Observable 1"
}
  • 在请求头中添加键为Content-Type、值为application/json的配置项。

内容的提问来源于stack exchange,提问作者Emiry Mirella

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 09:54:04