问题描述
我如何禁用模型验证了在控制器中单个动作?
或者,我可以做到这一点每个模型在启动时某个地方注册模型类型?
How do I disable Model validation for a single Action in a Controller ?Or can I do it per model by registering the model type at startup somewhere ?
我要ModelBinder的绑定到模型,但事后不应该进行模型验证。
I want the ModelBinder to bind to the model, but afterwards it should not perform the model validation.
为什么我不希望验证发生的原因是因为我试图逻辑从控制器将负责验证模型的一个服务层移动,因为我不能假定传递到一个服务模型包含有效数据
The reason why i dont want validation to happen is because i am trying to move the logic from the controllers to a service layer which will be responsible for validating the models as i cant assume that models being passed to a service contains valid data.
据我了解,这是建议的方法(不要在控制器逻辑),所以我觉得有些奇怪的是,我似乎无法找到有关模型验证如何可以禁用(每个动作或每个模型类型什么)。
As I understand this is the recommend approach (to not have logic in the controllers), so I find it a bit strange that i cant seem to find anything about how the model validation can be disabled (per action or per model type).
请注意,我不想禁用整个web应用模型验证(通过去除验证提供者),我不想禁用检查恶意code被张贴的输入验证。
Please notice that I dont want to disable model validation for the entire webapplication (by removing the validation providers), and i dont want to disable the input validation that checks for malicious code being posted.
我使用.NET 4.0和MVC 3 preVIEW 1
I am using .Net 4.0 and MVC 3 Preview 1
推荐答案
不幸的是似乎有禁用模型验证的ModelBinder的发生,除了注册的每一个机型没有简单的方法你不想验证(包括嵌套复杂类型)与特定ModelBinder的。它可以用下面code来完成:
Unfortunately there seems to be no easy way to disable the model validation happening in the ModelBinder except for registering every single model type you don’t want to validate (including nested complex types) with a specific ModelBinder. It can be done with the following code:
ModelBinders.Binders [typeof运算(MyModelType)] =新NonValidatingModelBinder();
创建可以附加到的操作方法或操作方法参数似乎并不可能,因为它应该在ControllerActionInvoker实现的SkipValidationAttribute,但也没有办法让ModelBinder的人都知道,它应该做任何验证中的SetProperty ()和OnModelUpdated方法调用BindModel()中GetParameterValue()方法。当
Creating a SkipValidationAttribute that can be attached to action methods or action method parameters doesn’t seem possible as it should be implemented in the ControllerActionInvoker, but there is no way of letting the ModelBinder know that it should do any validation in the SetProperty() and OnModelUpdated methods when calling BindModel() in the GetParameterValue() method.
这篇关于禁用模型验证在Asp.Net MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!