Post FromBody始终无效
我有一个新的API,我正在使用ASP.NET Core构建,我无法将任何数据POST到端点。
这是端点的样子:
[HttpPost] [Route("StudentResults")] public async Task GetStudentResults([FromBody]List userSocs, [FromBody]int collegeId) { var college = await _collegeService.GetCollegeByID(collegeId); // var occupations = await _laborMarketService.GetOccupationProgramsBySocsAndCollege(userSocs, college); return Ok(); }
这就是我通过Postman发送的有效载荷如下所示:
{ "userSocs": [ "291123", "291171", "312021", "291071", "152031", "533011" ], "collegeId": 1 }
我确保我将postman设置为POST,使用Content-Type application/json
。 我究竟做错了什么?
总是为null
因为您需要将所有post变量封装在一个对象中。 像这样:
public class MyPostModel { public List userSocs {get; set;} public int collegeId {get; set;} }
然后
public async Task GetStudentResults([FromBody] MyPostModel postModel)
如果模型为null,请检查:
1) 数据发送的地方:正文,表格? 并在此基础上添加装饰器到动作。 例如:
[HttpPost] public JsonResult SaveX([FromBody]MyVM vm) { ... }
2) 检查ModelState :如果它无效,则vm不会被绑定,因此它将为null。
if (ModelState.IsValid) { ... }
我知道这与你的情况无关,我仍然在这里发布我的答案。 我在代码中犯了一个愚蠢的错误。 我刚刚复制了我的一个Get请求并将其更改为Post请求,并忘了用[FromBody]
装饰参数。 如果其他人遇到同样的问题,请确保您使用[FromBody]
装饰参数。
[HttpPost] public IApiResponse Update([FromBody] User user) { if (user == null) return new ApiBadRequestResponse(ModelState); return _userService.Post(user) ? new ApiOkResponse(user) : new ApiResponse(500); }
如果你想发送两个以上的模型你应该使用这个例子,这对我有用,祝你好运
[HttpPost] public async Task addUsuario([FromBody] Newtonsoft.Json.Linq.JObject datos) { Usuarios user = datos["usuario"].ToObject(); Empresas empresa = datos["empresa"].ToObject(); return Json(await _srv.addUsuario(user, empresa)); }
- 找不到类型或命名空间名称“OpenIddictDbContext ”
- 如何在ASP.NET 5中修复CS0433错误?
- Asp.Net Core – 最简单的表单身份validation
- 如何在同一个项目中定位netcoreapp2.0和net461
- 有没有什么好的理由不在核心MVC中使用ViewComponent而不是Partial View?
- 从csproj引用ASP.NET xproj
- 从vNext中的appsetting.json读取启动外的连接字符串
- 将文件从ASP.NET Core web api发布到另一个ASP.NET Core web api
- 将查询参数绑定到ASP.NET Core中的模型