I'm using ASP.NET Core 2.0, and I have a request object annotated like this:
public class MyRequest
{
[Required]
public Guid Id { get; set; }
[Required]
public DateTime EndDateTimeUtc { get; set; }
[Required]
public DateTime StartDateTimeUtc { get; set; }
}
And in my controller:
public async Task<IActionResult> HandleRequest([FromBody] MyRequest request)
{ /* ... */ }
I noticed an issue with model binding: When I send a request containing the header Content-Type set to application/json and a an empty body, as I expect, the request in my controller is null and ModelState.IsValid is false.
But when I have a body like this:
{
"hello": "a-string-value!"
}
my request is NOT null, it has default values for everything, and ModelState.IsValid is true
This is happening of course while I'm missing all the Required properties, and the only existing one's name doesn't match a property there (even the type for this single parameter is string, which doesn't match any type on my model).
So in a way, those Required attributes seem to be working if there's nothing in my request, but they don't do anything if my request is not empty!
As I was preparing this question, I noticed that there's also a JsonRequired attribute, and it seems to take care of the properties being present.
So, what's the difference between Required and JsonRequired?