在 Asp.Net MVC 中禁用模型验证 [英] Disable Model Validation in Asp.Net MVC

查看:27
本文介绍了在 Asp.Net MVC 中禁用模型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为控制器中的单个操作禁用模型验证?或者我可以通过在某处启动时注册模型类型来为每个模型执行此操作吗?

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 应用程序的模型验证(通过删除验证提供程序),并且我不想禁用检查发布的恶意代码的输入验证.

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.可以使用以下代码完成:

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)] = new NonValidatingModelBinder();

创建一个可以附加到操作方法或操作方法参数的 SkipValidationAttribute 似乎不可能,因为它应该在 ControllerActionInvoker 中实现,但是没有办法让 ModelBinder 知道它应该在 SetProperty 中进行任何验证() 和 OnModelUpdated 方法在 GetParameterValue() 方法中调用 BindModel() 时.

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 中禁用模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆