Ale*_*ler 23 c# http-post asp.net-core
我有一个新的API,我正在使用ASP.NET Core构建,我无法将任何数据POST到端点.
这是端点的样子:
[HttpPost]
[Route("StudentResults")]
public async Task<IActionResult> GetStudentResults([FromBody]List<string> userSocs, [FromBody]int collegeId)
{
var college = await _collegeService.GetCollegeByID(collegeId);
// var occupations = await _laborMarketService.GetOccupationProgramsBySocsAndCollege(userSocs, college);
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
这就是我通过Postman发送的有效载荷如下所示:
{
"userSocs": [
"291123",
"291171",
"312021",
"291071",
"152031",
"533011"
],
"collegeId": 1
}
Run Code Online (Sandbox Code Playgroud)
我确保我将postman设置为POST,用Content-Type application/json.我究竟做错了什么?
Tin*_*wor 42
总是null因为你需要将所有的post变量封装在一个对象中.像这样:
public class MyPostModel {
public List<string> userSocs {get; set;}
public int collegeId {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
然后
public async Task<IActionResult> GetStudentResults([FromBody] MyPostModel postModel)
Run Code Online (Sandbox Code Playgroud)
gsx*_*y73 10
模型绑定失败(始终为 null)的另一个原因是属性的数据类型不匹配。例如,这是一个简单的模型:
public class MyService {
public string JobId { get; set; }
public int ServiceType {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
这是一些不匹配的json:
{"JobId":1, "ServiceType":1}
Run Code Online (Sandbox Code Playgroud)
当我使用 jquery 的 .data 函数检索 JobId 时,我遇到了这个问题,它会自动将其转换为 int。通过使用 .attr 函数来修复它。
如果模型为空,请检查:
1)数据发送到的位置:主体,形式?并基于此将装饰器添加到操作中。例如:
[HttpPost]
public JsonResult SaveX([FromBody]MyVM vm) { ... }
Run Code Online (Sandbox Code Playgroud)
2)检查ModelState:如果无效,则不会绑定虚拟机,因此它为null。
if (ModelState.IsValid) { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28058 次 |
| 最近记录: |