在这里,提出了一个问题,即如何验证不可为空的必需类型。
在我的情况下,不希望提供如下使字段为空的解决方案。
[Required]
public int? Data { get; set; }
Run Code Online (Sandbox Code Playgroud)
在请求中省略该字段的情况下,如何更改行为以进行以下失败验证。
[Required]
public int Data { get; set; }
Run Code Online (Sandbox Code Playgroud)
我尝试了一个自定义验证器,但是这些没有原始值的信息,只能看到默认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 …Run Code Online (Sandbox Code Playgroud)