.NET Core 3.1 API不接收Postman POST请求体报验证错误如何解决
问题原因
- CategoryDTO类的属性使用了私有set访问器:.NET Core 3.1默认使用的System.Text.Json序列化器不支持为私有set的属性赋值,请求体反序列化后Description和Observable属性均为null,直接触发Required验证规则。
- 代码存在多处拼写错误:
- 接口方法的参数类型写为
DTOs.CategotyDTO,正确类名应为CategoryDTO(拼写时遗漏了字母e) - 实例化Category时调用的
categoryDTO.Obervable属性名拼写错误,正确应为Observable(拼写时遗漏了字母s)
- 接口方法的参数类型写为
- Postman请求的JSON末尾存在多余逗号,部分严格的JSON解析器会判定该格式非法。
- 若未主动配置请求头,可能缺少
Content-Type: application/json标识,导致服务端无法正确识别JSON格式的请求体。
解决方案
- 将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; });
- 修正所有拼写错误:
- 将接口参数类型改为
DTOs.CategoryDTO - 将代码中
categoryDTO.Obervable改为categoryDTO.Observable
- 调整Postman请求配置:
- 移除JSON末尾的多余逗号:
{ "Description": "Category 1", "Observable": "Observable 1" }
- 在请求头中添加键为
Content-Type、值为application/json的配置项。
内容的提问来源于stack exchange,提问作者Emiry Mirella
相关产品推荐
相关产品推荐

