ASP.NetCore2MVC中禁用模型验证的正确方法使用扩展方法设置MVCservices.AddMvc()然后在controller中,这也可以应用于GET,使用字面量中提供的参数创建POST操作的方法,eg[HttpPost("save")]publicEntitySave([FromBody]EntitysomeEntity)时调用操作时,MVC管道将调用ParameterBinder,后者又调用DefaultObjectValidator。我不想验证(有一件事很慢,但更重要的是循环复杂的循环图),但似乎关闭管道验证的唯一方法是这样的:validationState,stringprefix,objectmodel){}}在StartUp/ConfigureServices中:varvalidator=services.FirstOrDefault(s=>s.ServiceType==typeof(IObjectModelValidator));如果(验证器!=null){services.Remove(验证器);services.Add(newServiceDescriptor(typeof(IObjectModelValidator),_=>newNonValidatingValidator(),ServiceLifetime.Singleton));这看起来像一把大锤。我环顾四周,找不到替代方案,还尝试删除DataAnnotationModelValidator但没有成功,所以想知道是否有更好/正确的方法来关闭验证?services.Configure(options=>{options.SuppressModelStateInvalidFilter=true;});应该禁用自动模型状态验证。.AddMvc()扩展方法有一个重载,您可以在其中配置很多东西。其中之一是ModelValidatorProviders列表。如果您清除此列表,例如:services.AddMvc(options=>options.ModelValidatorProviders.Clear());验证不应该再发生了。使用这种扩展方法:publicstaticIServiceCollectionDisableDefaultModelValidation(thisIServiceCollectionservices){ServiceDescriptorserviceDescriptor=services.FirstOrDefault((Func)(s=>s.ServiceType==typeof(IObjectModelValidator)));if(serviceDescriptor!=null){services.Remove(serviceDescriptor);services.Add(newServiceDescriptor(typeof(IObjectModelValidator),(Func)(_=>(object)newEmptyModelValidator()),ServiceLifetime.Singleton));}退货服务;}publicclassEmptyModelValidator:IObjectModelValidator{publicvoidValidate(ActionContextactionContext,ValidationStateDictionaryvalidationState,stringprefix,objectmodel){}}用法:publicvoidConfigureServices(IServiceCollectionservices){services.DisableDefaultModelValidation();}创建空间模型验证器类。publicclassEmptyModelValidator:IObjectModelValidator{publicvoidValidate(ActionContextactionContext,ValidationStateDictionaryvalidationState,stringprefix,objectmodel){}}在配置服务方法中,将DefaultModelValidator替换为EmptyModelValidator。services.Replace(newServiceDescriptor(typeof(IObjectModelValidator),typeof(EmptyModelValidator),ServiceLifetime.Singleton));EmptyModelValidator不验证模型,因此ModelState.IsValid始终返回false。以上就是C#学习教程的全部内容:ASP.NetCore2MVC中禁用模型验证的正确方法。如果对你有用,需要了解更多C#学习教程,希望大家多加关注——本文来自网络合集,不代表立场,如涉及侵权,请点击有权联系管理员删除。如需转载请注明出处:
