使用 Postman 请求示例:
一, 在 Headers 要声明请求类型 Content-Type
二, body 提交要使用 raw, 且声明为 JSON 格式传输
三, 如果有 authorization 验证还需要带上 (如果没有直接忽略)
关于 Postman 提交请求, Controller 无法获取对象的原因分析:
1, 先贴代码
- /// <summary>
- /// 修改用户信息
- /// </summary>
- /// <param name="patch"></param>
- /// <returns></returns>
- [Route("Patch")]
- [HttpPatch]
- [ProducesResponseType(typeof(AppUser), StatusCodes.Status200OK)]
- [ProducesResponseType(typeof(Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary), StatusCodes.Status400BadRequest)]
- [ProducesDefaultResponseType]
- public async Task<IActionResult> PatchAsync([FromBody]JsonPatchDocument<AppUser> patch)
- {
- }
1, 声明控制器请求方式必须为:[HttpPatch]
2, 接收使用 [FromBody], 且需要使用 JsonPatchDocument<T> patch 来实现对象的解析
3-1, 在 Net core3.0 以后, 微软移除了 Newtonsoft.JSON, 而使用了 System.Text.JSON, 所以依赖于 Newtonsoft.JSON 的组件将不可用, 需要安装 包
3-2, 为 Controllers 添加 NewtonsoftJson 注册, 在 Startup.cs 下
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllers() .AddNewtonsoftJson();
- }
请记住, 在 Net core3.0 以后, 一定要注册, 否则会遇到一下 400 错误
The JSON value could not be converted to Microsoft.AspNetCore.JsonPatch.JsonPatchDocument`1[User.API.Models.AppUser]. Path
原因为程序无法正常解析该 JSON, 因为没有找到 NewtonsoftJson 包的依赖; 关于微软为何要移除该包的依赖, 主要是为了提升执行效率; System.Text.JSON 作为微软内置 JSON 处理, 效率更高更快, 但是目前大部分主流的包还是使用的 NewtonsoftJson 开发.
来源: http://www.bubuko.com/infodetail-3363245.html