我有一个post方法,每次调用参数School
时总是为null。我确保发送正确的数据,我正在使用Postman,但是当我用断点检查它时,我得到一个空对象。
我与邮递员发送的内容:
{
"Id": "",
"Name": "Test"
}
控制器:
[HttpPost]
public IActionResult Post([FromBody] School school)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var schoolData = Mapper.Map<School, Data.School>(school);
var schoolModel = _schoolRepository.AddSchool(schoolData);
return CreatedAtRoute("GetSchool", new { id = schoolModel }, schoolModel);
}
catch (Exception e)
{
return LogException(e);
}
}
型号:
public class School
{
public Guid Id { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
public IEnumerable<Teacher> Teachers { get; set; }
public IEnumerable<Class> Classes { get; set; }
}
答案 0 :(得分:1)
问题是您的模型需要Guid
并且您要发送empty string
:
"Id": ""
无论Id
不是[Required]
,模型仍然无法解析数据。但是,您可以做的是将其排除在绑定之外:
public IActionResult Post([FromBody][Bind(Include = nameof(School.Name))] School school)
或者,更好的选择是使用ViewModel。但是,在这种情况下,由于您只有一个属性,我只是使用它:
public IActionResult Post([FromBody]string name)