简体   繁体   中英

How to add Boolean validation for a model property WebApi .NET Core using data annotation

I am trying to validate below property using annotation, either it should be true or false

public bool Info { get; set; }

I will get a invalid data validation error if i pass json like below

{  
  "info": trues
}

But strange if i pass like below, no data validation.

 { "info": 12345 }

I had tried with ValidationAttribute like below, but value is always true even if val is 12345

public class IsBoolAttribute : ValidationAttribute
{
    //public override bool RequiresValidationContext => true;

    public override bool IsValid(object value)
    {

        if (value == null) return false;
        if (value.GetType() != typeof(bool)) return false;
        return (bool)value;
    }
}

If you use Newtonsoft.Json in Startup.cs , it seems to convert the random integer to true by design . You could write a custom JsonConverter like below:

public class CustomBoolConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var value = reader.Value;

        if (value.GetType() != typeof(bool))
        {
            throw new JsonReaderException("The JSON value could not be converted to System.Boolean.");
        }
            return value;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value as string);
    }
}

Startup.cs

services.AddControllers()
            .AddNewtonsoftJson();

Alternative method , you could use System.Text.Json which is by default since ASP.NET Core 3.0 , Startup.cs like below:

services.AddControllers();
        //.AddNewtonsoftJson();

It will return the below error when you input incorrect value: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM