1

Let's say there's a PUT request coming from my client, I want to process this data. with the FromBody attribute I can get the bound data. But when there's no data bound to my [FromBody] object I want to send 400 to my client. Because if I don't, I will update my database with an object who's members are null/default for no reason. How do I get around this in .NET 5?

an example function definition would be: public async Task<IActionResult> PutAsync(long id, [FromBody] PersonUpdateDto personUpdateModel)

    public class PersonUpdateDto {
    public string Name {get; set;}
    public string Surname {get; set;}
    }

Again, I want to return 400 to my client if all the members in personUpdateModel is null.(which means no bind operation happened)

sercan tor
  • 23
  • 6
  • 1
    From what you've posted, this sounds like you just want a simple `if` statement at the top of your function. Have you already tried that? – gunr2171 Dec 29 '21 at 13:26
  • Try adding [Required](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.requiredattribute?view=net-6.0) attribute to Name and Surname fields in the PersonUpdateDto class – Matt.G Dec 29 '21 at 13:26
  • @Matt.G Required would not be a good design for a `PUT` endpoint as the client can choose to not update a certain field. – sercan tor Dec 29 '21 at 13:34
  • @gunr2171 if you can provide me with an example `if` statement, I would appreciate it – sercan tor Dec 29 '21 at 13:34

1 Answers1

2

If you use the [ApiController] attribute on your controller, it will handle the serialization errors and provide the 400 response for you. it's actually equivalent to:

if (!ModelState.IsValid)
{
   return BadRequest(ModelState);
}

You can read more about it here - https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2#automatic-http-400-responses

Ran Turner
  • 14,906
  • 5
  • 47
  • 53
  • yeah, I'm using `[ApiController]` attribute on my controller, correct me if I'm wrong, isn't this for data annotations? I don't have a data annotation in my model, because it's an updateDTO, all fields should be optional, but I want to validate at least one field has been bound with data. – sercan tor Dec 29 '21 at 13:42