Using Required and JsonRequired in ASP.NET Core Model Binding with JSON body

后端 未结 3 1903
北海茫月
北海茫月 2021-01-12 07:00

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; }

    [         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-12 07:13

    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.

提交回复
热议问题