Here's my model
public class TaskForUpdateDTO
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Name { get; set; }
}
and my controller
[HttpPut]
public ActionResult<List<TaskDTO>> Put([FromBody] List<TaskForUpdateDTO> tasks )
{
List<TaskBO> tasksForUpdate = TaskForUpdateDTO.MapToBOList(tasks);
tasksForUpdate = _serviceManager.TaskService.Update(tasksForUpdate);
if (tasksForUpdate is null) return NotFound();
return Ok(TaskDTO.MapToDTOList(tasksForUpdate));
}
and body of my request
[{
"Name":"Do Laundry",
"UserId":1
},
{
"Name":"Wash Dishes",
"UserId":1
}]
when sending a PUT request, I'm not getting a 400 error , which I should because I'm not sending the Id of the item.
how can I fix this?
The Required
Attribute only check for null.
The Default value of an int
is simply "0"(zero). So, it is not null when Required
attribute check it.
If you Prefer to use the Required
attribute then replace your int
to int?
(Nullable int. The Default Value of Nullable int is null
And can double-Check with it's static .HasValue()
method)
Or if you need to check that not pass the value when value is Zero or Less then you can use Range
Attribute
Usage of Range Attribute
:
[Range(1, Int32.MaxValue)]
public int Id {get;set;}
Simply you can change the Int32.MaxValue
to your Maximum acceptable integer of your needs.
Hope this helps.