【问题标题】:How to add Boolean validation for a model property WebApi .NET Core using data annotation如何使用数据注释为模型属性 WebApi .NET Core 添加布尔验证
【发布时间】:2020-01-20 07:51:36
【问题描述】:

我正在尝试使用注释验证下面的属性,它应该是真还是假

public bool Info { get; set; }

如果我像下面这样传递 json,我会得到一个无效的数据验证错误

{  
  "info": trues
}

但奇怪的是,如果我像下面这样通过,没有数据验证。

{  
  "info": 12345
}

我曾尝试使用ValidationAttribute,如下所示,但即使 val 为 12345

value 始终为 true
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;
    }
}

【问题讨论】:

  • 尝试使用可以为空的布尔值?操作员。在您的情况下,如果 mvc 无法解析值,它将是错误的。但是如果 yomake 它可以为空,如下 public bool?信息{得到;放;如果传递了无效数据,} 值将为 null。
  • @Hemant 感谢您的评论,我试过了,但没有希望

标签: c# asp.net-core model webapi


【解决方案1】:

如果您在 Startup.cs 中使用 Newtonsoft.Json ,它似乎将随机整数转换为 true 设计。您可以编写一个自定义的 JsonConverter,如下所示:

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();

另一种方法,您可以使用System.Text.Json,这是自 ASP.NET Core 3.0 以来的默认设置,Startup.cs 如下所示:

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

输入不正确的值会返回以下错误:

【讨论】:

    猜你喜欢
    • 2015-12-14
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多