Исключение NullReferenceException при использовании Fluent Validation ASP.NET сердечник
Всякий раз, когда я подключаю fluent validation к своему asp.net core MVC app я начинаю получать NullReferenceException , я следовал руководству по интеграции для asp.net ядро на github, но я не могу понять, где сбой. ниже приведен мой класс модели валидатор и конфигурация службы
Public void ConfigureServices (службы IServiceCollection) {
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));
}
Мой класс модели и валидатор
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;
}
}
Это трассировка стека
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()
Вот как я себя чувствую. выполнение представления
public IActionResult Index()
{
var model = new BookingSearchViewModel();
return View(model);
}
Я пытался удалить свойства, допускающие обнуление в модели, инициализировать их, удалить правила проверки, но я все равно получаю ту же ошибку, я использую FluentValidation.В7 AspNetCore.2.0.
Как я могу исправить это нулевое исключение?
**Edit:
Не является дубликатом, связан с Fluent Validation, и я предполагаю, что исключение происходит при введении Fluent validation в asp.net ядро, ни одна из моих моделей не является нулевой, удаляя AddFluentValidation() из служб удаляет ошибку, но тогда я больше не могу использовать fluent validation * *
Спасибо
1 ответ:
Не уверен, нужна ли вам проверка на стороне клиента для вашего конкретного приложения, но мне удалось разобраться с этим, отключив проверку на стороне клиента (после чтения журнала fluentvalidation issues log здесь)
Код, который я использую при запуске: -
services.AddMvc().AddFluentValidation(fv => { fv.ConfigureClientsideValidation(enabled: false); });