gpt4 book ai didi

c# - 使用 Fluent Validation ASP.NET Core 时出现 NullReferenceException

转载 作者:太空宇宙 更新时间:2023-11-03 12:21:47 24 4
gpt4 key购买 nike

每当我将流畅的验证连接到我的 asp.net core mvc 应用程序时,我开始收到 NullReferenceException,我已经按照 github 上的 asp.net core 集成指南进行操作,但我无法理解失败的地方。下面是我的模型类、验证器和服务配置

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()

这就是我执行 View 的方式

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

我已经尝试删除模型中的可空属性、初始化它们、删除验证规则,但我仍然遇到相同的错误,我使用的是 FluentValidation.AspNetCore v7.2.0。

如何解决这个空异常?

**编辑:

不是重复的,与 Fluent Validation 相关,我猜想在将 Fluent 验证注入(inject) asp.net core 时发生异常,我的模型都不是 null,从服务中删除 AddFluentValidation() 会删除错误,但随后我不能再使用流畅的验证了**

谢谢

最佳答案

不确定您是否需要为您的特定应用程序启用客户端验证,但我设法通过禁用客户端验证来对此进行排序(在阅读流畅验证问题日志 here 之后)

我在启动时使用的代码是:-

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

关于c# - 使用 Fluent Validation ASP.NET Core 时出现 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46860232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com