3
votes

whenever I hook up fluent validation to my asp.net core mvc app I start getting NullReferenceException, I've followed the integration guide for asp.net core on github but I can't figure it out where is failing. bellow is my model class an validator and service configuration

public void ConfigureServices(IServiceCollection services) {

  var appSettings = Configuration.GetSection("AppSettings");
  services.Configure<AppSettings>(appSettings);


  #region FluentValidation
  services.AddTransient<IValidator<ContactFormModel>, ContactFormValidator>();
  services.AddTransient<IValidator<BookingSearchViewModel>, BookingSearchModelValidator>();
  services.AddTransient<IValidator<BookingCarSelectionViewModel>, BookingCarSelectionValidator>();
  services.AddTransient<IValidator<BookingClientDataModel>, BookingClientDataValidator>();
  #endregion


  services.AddMvc().AddFluentValidation();
  services.AddAutoMapper(typeof(Startup));      
}

my model class and validator

public class BookingSearchViewModel
  {
    [Display(Name ="Fecha de Recogida")]
    public DateTime? PickupDate { get; set; }

    [Display(Name = "Fecha de Entrega")]
    public DateTime? DropoffDate { get; set; }

    [Display(Name = "Transmisión")]
    public CarTransmissionEnum Transmission { get; set; }

    public List<SelectListItem> transmissionOptions { get; set; }

    public BookingSearchViewModel()
    {

      var list = new List<string>
      {
        "Manual",
        "Automatico"
      };

      this.transmissionOptions = new List<SelectListItem> {
        new SelectListItem
        {
          Text="Manual"
        },
        new SelectListItem
        {
          Text="Automatico"
        }
      };
    }

  }
  public class BookingSearchModelValidator : AbstractValidator<BookingSearchViewModel>
  {
    public BookingSearchModelValidator()
    {
      RuleFor(x => x.PickupDate).NotNull().GreaterThan(DateTime.Now).Must(FiveDaysFromToday);
      RuleFor(x => x.DropoffDate).NotNull().GreaterThan(x => x.PickupDate).Must((form, countyId) => BeAValidRange(form.PickupDate, form.DropoffDate));
      RuleFor(x => x.Transmission).IsInEnum();
    }

    private bool FiveDaysFromToday(DateTime? pickupDate)
    {
      if (pickupDate.HasValue)
      {
        var today = DateTimeOffset.UtcNow.Date.ToCST().DateTime;
        var days = pickupDate.Value.Date.ToCST().Subtract(today).Days;
        return days > 3;
      }
      return false;
    }

    private bool BeAValidRange(DateTimeOffset? pickupDate, DateTimeOffset? dropoffDate)
    {
      if (pickupDate.HasValue && dropoffDate.HasValue)
      {
        var days = dropoffDate.Value.Subtract(pickupDate.Value).Days;
        if (days > 2 && days < 29)
          return true;
      }
      return false;
    }

  }

this is the stack trace

NullReferenceException: Object reference not set to an instance of an object.
FluentValidation.AspNetCore.FluentValidationClientModelValidatorProvider.CreateValidators(ClientValidatorProviderContext context)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.CompositeClientModelValidatorProvider.CreateValidators(ClientValidatorProviderContext context)
Microsoft.AspNetCore.Mvc.Internal.ClientValidatorCache.GetValidators(ModelMetadata metadata, IClientModelValidatorProvider validatorProvider)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultValidationHtmlAttributeProvider.AddValidationAttributes(ViewContext viewContext, ModelExplorer modelExplorer, IDictionary<string, string> attributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.ValidationHtmlAttributeProvider.AddAndTrackValidationAttributes(ViewContext viewContext, ModelExplorer modelExplorer, string expression, IDictionary<string, string> attributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.AddValidationAttributes(ViewContext viewContext, TagBuilder tagBuilder, ModelExplorer modelExplorer, string expression)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateInput(ViewContext viewContext, InputType inputType, ModelExplorer modelExplorer, string expression, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, string format, IDictionary<string, object> htmlAttributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateTextBox(ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, string format, object htmlAttributes)
Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.GenerateTextBox(ModelExplorer modelExplorer, string inputTypeHint, string inputType)
Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Process(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner+<RunAsync>d__0.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
AspNetCore._Views_Home_Index_cshtml+<<ExecuteAsync>b__39_7>d.MoveNext() in Index.cshtml
+
                  <input asp-for="PickupDate" class="form-control" placeholder="mm/dd/yyyy" required type="text" />
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext+<GetChildContentAsync>d__31.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper+<ProcessAsync>d__7.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner+<RunAsync>d__0.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
AspNetCore._Views_Home_Index_cshtml+<ExecuteAsync>d__39.MoveNext() in Index.cshtml
+
    var pixelImage = appSettings.Value.PixelImage;
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderPageCoreAsync>d__16.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderPageAsync>d__15.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderAsync>d__14.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor+<ExecuteAsync>d__22.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor+<ExecuteAsync>d__21.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.ViewResult+<ExecuteResultAsync>d__26.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeResultAsync>d__19.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResultFilterAsync>d__24.MoveNext()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResourceFilter>d__22.MoveNext()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeFilterPipelineAsync>d__17.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeAsync>d__15.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()

this is how I'm executing the view

public IActionResult Index()
    {
      var model = new BookingSearchViewModel();
      return View(model);
    }

I've tried removing the nullable properties in the model, initializing them, removing the validation rules but I still get the same error , I'm using FluentValidation.AspNetCore v7.2.0.

How can I fix this null exception?

**Edit:

is not a duplicate, is related to Fluent Validation and my guess the exception is happening when Injecting Fluent validation into asp.net core, none of my models are null, removing the AddFluentValidation() from the services removes the error but then I can't use fluent validation no more**

Thanks

1
is not a duplicate, is related to Fluent Validation and my guess the exception is happening when Injecting Fluent validation into asp.net core, none of my models are null, removing the AddFluentValidation() from the services removes the error but then I can't use fluent validation no moreGeneral Electric

1 Answers

1
votes

Not sure if you need client side validation on for your particular application, but I managed to sort this by disabling client side validation (after reading the fluentvalidation issues log here)

The code I use in my startup is:-

services.AddMvc().AddFluentValidation(fv => 
{    
    fv.ConfigureClientsideValidation(enabled: false);
});