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.
Yes, the difficulty is that if you choose Required, the semantics for the client of the web request change incorrectly - i.e. you are saying you can pass in a null, when you really need a proper value.
Using JsonRequired sorts this, but this is provided by NewtonSoft, so stops working when you upgrade to .Net Core 3. This is because .Net Core 3 uses its own Json parser instead of NewtonSoft.
When you use [FromBody]
as binding source, the Model properties will get default values and [BindRequired]
will be ignored.
There is a related issue on "Problems with Parameter Validation".
In this case is better to use [JsonRequired]
instead of [BindRequired]
to enforce binding properties.
Note that [JsonRequired]
affects serialization and deserialization both.