猿问

在ASP.NET Core中的操作方法上禁用模型验证

我想在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();

}   


梵蒂冈之花
浏览 617回答 3
3回答

HUWWW

实现了自己的目标,仅在验证器中放置了一个RuleSet。当管道调用验证程序时,它不会进行验证,因为管道调用没有RuleSet。贝娄是我如何解决此问题的一个示例:public class CustomerValidator : AbstractValidator<Customer>{&nbsp; &nbsp; public CustomerValidator()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; RuleSet("Manually", () =>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RuleFor(x => x.Surname).NotNull();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RuleFor(x => x.Forename).NotNull();&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}public ActionResult ActionWithoutValidationExecuted(Customer customer)&nbsp;{&nbsp; &nbsp; //..... Manually binding customer...&nbsp; &nbsp; var validator = new CustomerValidator();&nbsp; &nbsp; var validResult = validator.Validate(customer, ruleSet: "Manually");&nbsp; &nbsp; // Doing something more ........&nbsp; &nbsp; return Ok();}
随时随地看视频慕课网APP
我要回答