3

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;
    }
}
2
  • Try nullable boolean using ? Operator. In your case if mvc is not able to parse value it wiuld be false. But if yomake it nullable as follows public bool? Info { get; set; } value will be null if invalid data is passed. Commented Jan 20, 2020 at 7:54
  • 1
    @Hemant thanks for the comment, i tried, but no hope Commented Jan 20, 2020 at 8:12

1 Answer 1

2

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: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.