c# - 为 POST 和 PUT 请求获取有效负载为空
问题描述
我制作了 POST 和 PUT API,现在我正在做属性验证,
模型
public class Model
{
public string user_identifier { get; set; }
public string name { get; set; }
}
邮递员中的有效载荷
{
"user_identifier": "1234",
"name": "abcd"
}
它适用于此,但是当我更改 user_identifier 的类型时,
{
"user_identifier": 1234,
"name": "abcd"
}
Postman 为该属性提供了一个自动 400 错误,我不想要,因为我正在做自己的验证,所以,我添加了这个来抑制那些自动 400 响应,
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
现在,当我传递有效载荷时,
{
"user_identifier": 1234,
"name": "abcd"
}
有效载荷被认为是空的,任何人都可以帮我解决这个问题,而且我认为抑制自动响应并不好,将不胜感激。
提前致谢。
解决方案
主要问题是,当您的 json 如下所示时,它说的user_identifier
是 anint
但您说它应该是string
.
{
"user_identifier": 1234,
"name": "abcd"
}
这是在新创建的 api 项目上返回的错误。
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|8c6385fc-4816d0c11a257a60.",
"errors": {
"$.user_identifier": [
"The JSON value could not be converted to System.String. Path: $.user_identifier | LineNumber: 1 | BytePositionInLine: 27."
]
}
}
一旦您知道这是问题所在(假设您使用的是 ASP.NET Core >= 3.0.0),您会发现JSON 值无法转换为 System.Int32,这解释了它们是如何从 ASP.NET 中的 Json.NET 迁移而来的核心 3.0.0。一种选择是Microsoft.AspNetCore.Mvc.NewtonsoftJson
在启动时安装并添加它services.AddControllers().AddNewtonsoftJson();
推荐阅读
- python - do_handshake 中有什么意义
- java - 在 Java 中创建 HTML 表
- reactjs - TypeError: this.state.data.map 在 Heroku 上部署时不是一个函数,但在本地工作
- django - 使用相关对象的外键预取或注释 Django 模型
- mysql - 在 MySQL 中搜索 JSON 数据中的属性的 SQL 查询
- mobile - 服务器端渲染是否适合移动应用?
- robotframework - 在机器人框架测试用例创建自定义库类的新实例时传递参数
- jquery - 显示/隐藏 onClick JQuery
- lisp - 在 lisp 中更改数组值的最佳方法
- spark-java - 从模板中查找路由/url?(Java Spark 框架)