Asp.NET MVC-在控制器外部验证模型 [英] Asp.NET MVC - Validate a Model Outside of the Controller

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

问题描述

我正在构建一个ASP.NET MVC项目,并采用以下体系结构:

I am building an ASP.NET MVC project and going for the following Architecture:

  • 具有模型,验证,dto,逻辑等的 Core 项目.
  • 作为我的REST API的 ServiceStack API 项目
  • 作为用户界面的 ASP.NET MVC Web 项目
  • A Core project that has models, validation, dto, logic, etc.
  • A ServiceStack API project that acts as my REST API
  • An ASP.NET MVC Web project that is the UI

因此,假设我要添加一个用户.我在 Core 项目中定义了NewUserInputModel.我给它一些数据注释,例如[Required].完成此操作后, Web 项目将基于这些注释执行客户端验证.

So, let's say I want to add a user. I define a NewUserInputModel in the Core project. I give it some data annotations such as [Required]. After doing this, the Web project will perform client side validation based on those annotations.

我的问题是关于服务器端验证的.我想使用客户端使用的相同规则来验证NewUserInputModel,并且我想运行NewUserInputModel来自 API 的验证天气网络项目.

My question is about server side validation. I want to validate the NewUserInputModel using the same rules that are being used on the client side, and I want to run that validation weather the NewUserInputModel comes in from the API or the Web project.

我意识到我可以从 Web 项目中的Controller调用ModelState.IsValid-但我想从 Core 项目中调用该验证,以便所有验证逻辑都有效在核心中.这样,无论该模型如何使用 Core 逻辑,我总是调用相同的验证.我不想将System.Web引用泄漏到我的 Core 项目中.

I realize I could call ModelState.IsValid from a Controller in the Web project - but I want to call that validation from the Core project so that all validation logic lives in Core. This way, no matter how this model gets to the Core logic, I always call the same validation. I don't want to leak a System.Web reference into my Core project.

这是合理的设计吗?我认为是-但如果闻到某种气味,我会很高兴听到它.

Is this a reasonable design? I think it is - but if something about it smells, I'd be happy to hear it.

在此先感谢您的帮助.

推荐答案

我通常将视图模型保留在Web项目中,并使用ModelState属性在控制器中进行 input 验证.如果成功,则将它们映射到域模型(位于Core层中),然后将其发送到Service(也可以是Core)层中的服务.服务层验证业务规则,如果成功,它将调用存储库以执行所需的操作,并将操作结果返回给控制器.

I usually keep my view models in the Web project and do the input validation in the controller using the ModelState property. If this succeeds, I map them to domain models (which live in the Core layer) and send those to my services in the Service (could also be Core) layer. The service layer validates business rules and if it succeeds it calls a repository to perform the desired action and returns the result of the operation to the controller.

在Web项目中保留视图模型还使您可以使用MVC验证属性,例如

Keeping your view models in the Web project also allows you to use MVC validation attributes such as RemoteAttribute.

我并不是说您的设计闻起来,但我认为将表示逻辑与您的Core层分开是很好的.

I'm not saying that your design smells, but I do think it's good to separate presentation logic from your Core layer.

这篇关于Asp.NET MVC-在控制器外部验证模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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