Here https://stackoverflow.com/questions/6662976/required-attribute-for-an-integer-value,提出了如何验证不可为空的必需类型的问题。
在我的情况下,提供的使字段可为空的解决方案如下所示是不可取的。
[Required]
public int? Data { get; set; }
在请求中省略该字段的情况下,如何更改行为以使以下验证失败。
[Required]
public int Data { get; set; }
我尝试过自定义验证器,但这些验证器没有有关原始值的信息,只能看到默认值0
价值。我也尝试过自定义模型绑定器,但它似乎在整个请求模型的级别上工作,而不是在需要的整数字段级别上工作。我的活页夹实验如下所示:
public class RequiredIntBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(int))
throw new InvalidOperationException($"{nameof(RequiredIntBinder)} can only be applied to integer properties");
var value = bindingContext.ValueProvider.GetValue(bindingContext.BinderModelName);
if (value == ValueProviderResult.None)
{
bindingContext.Result = ModelBindingResult.Failed();
return Task.CompletedTask;
}
return new SimpleTypeModelBinder(bindingContext.ModelType).BindModelAsync(bindingContext);
}
}
public class RequiredIntBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.ModelType == typeof(int))
{
return new BinderTypeModelBinder(typeof(RequiredIntBinder));
}
return null;
}
}
并像这样向 mvc 注册
options.ModelBinderProviders.Insert(0, new RequiredIntBinderProvider());
但模型绑定器从未被使用过。我觉得我可能很接近,但无法连接最后的点。
使用 json 请求的解决方案
You 无法验证已创建的模型实例,因为不可为 null 的属性始终具有一个值(无论它是从 json 分配还是默认值)。这解决方案是在反序列化期间报告缺失值.
创建合约解析器
public class RequiredPropertiesContractResolver : DefaultContractResolver
{
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
foreach (var contractProperty in contract.Properties)
{
if (contractProperty.PropertyType.IsValueType
&& contractProperty.AttributeProvider.GetAttributes(typeof(RequiredAttribute), inherit: true).Any())
{
contractProperty.Required = Required.Always;
}
}
return contract;
}
}
然后将其分配给SerializerSettings
:
services.AddMvc()
.AddJsonOptions(jsonOptions =>
{
jsonOptions.SerializerSettings.ContractResolver = new RequiredPropertiesContractResolver();
});
The ModelState
那么对于不可为 null 的属性无效[Required]
属性(如果 json 中缺少该值)。
Example
json体
var jsonBody = @"{ Data2=123 }"
对于型号无效
class Model
{
[Required]
public int Data { get; set; }
public int Data2 { get; set; }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)