title: ASP.NET Core [Require] non-nullable types
body: <p><a href="https://stackoverflow.com/questions/6662976/required-attribute-for-an-integer-value">Here</a>, the question was posed how to validate non-nullable required types.</p>
  
  <p>The provided solution to make the field nullable like the following is not desirable in my case.</p>
  
  <pre><code>[Required]
  public int? Data { get; set; }
  </code></pre>
  
  <p>How can you change the behavior to instead make the following fail validation in the cases where the field is omitted from the request.</p>
  
  <pre><code>[Required]
  public int Data { get; set; }
  </code></pre>
  
  <p>I have tried a custom validator, but these do not have information about the raw value and only see the default <code>0</code> value. I have also tried a custom model binder but it seems to work at the level of the entire request model instead of the integer fields which a want. My binder experiment looks like this:</p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>and is registered with mvc like this</p>
  
  <pre><code>options.ModelBinderProviders.Insert(0, new RequiredIntBinderProvider());
  </code></pre>
  
  <p>but the model binder is never used. I feel like I might be close but cannot connect the last dots.</p>