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; }
[
For correct work of Required
attribute, you should make the properties nullable:
public class MyRequest
{
[Required]
public Guid? Id { get; set; }
[Required]
public DateTime? EndDateTimeUtc { get; set; }
[Required]
public DateTime? StartDateTimeUtc { get; set; }
}
Now if you send request with missing Id
, EndDateTimeUtc
or StartDateTimeUtc
, corresponding field will be set to null
, ModelState.IsValid
will be set to false
and ModelState
will contain error(s) description, e.g. The EndDateTimeUtc field is required.
JsonRequired
attribute is specific to JSON.Net. It plays during deserialization, while Required
attribute (as other attributes from System.ComponentModel.DataAnnotations
namespace) plays after model is deserialized, during model validation. If JsonRequired
attribute is violated, the model will not be deserialized at all and corresponding action parameter will be set to null
.
The main reason why you should prefer Required
attribute over JsonRequired
is that JsonRequired
will not work for other content types (like XML). Required
in its turn is universal since it's applied after the model is deserialized.