我想在Controller中的特定Action方法上禁用模型验证。我有这种情况:public class SomeDto{ public string Name { get; set; }}public class SomeDtoValidator : AbstractValidator<SomeDto>, ISomeDtoValidator{ public SomeDtoValidator () { RuleFor(someDto=> someDto.Name).NotNull().WithMessage("Name property can't be null."); }}我有ISomeDtoValidator,因为我以自己的方式注册了所有验证器:public class Startup{ // .... constructor .... public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.AddMvc(setup => { //...others setups... }).AddFluentValidation(); services.RegisterTypes(Configuration) .RegisterFluentValidation() .RegisterMappingsWithAutomapper() .RegisterMvcConfigurations(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConfiguration configuration) { // ... }}我在控制器中有此操作方法:[DisableFormValueModelBinding]public async Task<IActionResult> CreateSome(Guid someId, SomeDto someDto){ //..... Manually binding someDto... var validator = new SomeValidator(); validator.Validate(someDto); // Doing something more ........ return Ok();} 我禁用了ModelBinding的MVC,因为我想在绑定SomeDto之前做一些事情,因此,我也不想在SomeDto上应用任何验证器。因此,有什么方法可以实现?例如,如下所示:[DisableValidator] // Or [DisableValidator(typeof(SomeDtoValidator))] whatever[DisableFormValueModelBinding]public async Task<IActionResult> CreateSome(Guid someId, SomeDto someDto){ //..... Manually binding someDto... var validator = new SomeValidator(); validator.Validate(someDto); // Doing something more ........ return Ok();}
3 回答
HUWWW
TA贡献1874条经验 获得超12个赞
实现了自己的目标,仅在验证器中放置了一个RuleSet。当管道调用验证程序时,它不会进行验证,因为管道调用没有RuleSet。贝娄是我如何解决此问题的一个示例:
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleSet("Manually", () =>
{
RuleFor(x => x.Surname).NotNull();
RuleFor(x => x.Forename).NotNull();
});
}
}
public ActionResult ActionWithoutValidationExecuted(Customer customer)
{
//..... Manually binding customer...
var validator = new CustomerValidator();
var validResult = validator.Validate(customer, ruleSet: "Manually");
// Doing something more ........
return Ok();
}
- 3 回答
- 0 关注
- 601 浏览
添加回答
举报
0/150
提交
取消