.net核心MVC瘦控制器 - 服务层 [英] .net core MVC thin controlers - service layer

查看:80
本文介绍了.net核心MVC瘦控制器 - 服务层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用服务层来细化我的控制器。但我无法锻炼或找到如何处理服务层中出现的问题的示例。



例如,我有一个控制器动作Add Item,有一个名字和用户定义的ID。



代码在数据库中必须是唯一的。



所以我的控制器只需获取视图模型并将其传递给ItemService.Add()

添加内部是检查ID是否存在的逻辑。如果不是,控制器需要将该信息发送回用户并让他们改变他们的输入。



那么如何将该信息发送回控制器,以便存储错误信息并显示正确的视图?



有没有一种标准的方法可以做到这一点,几乎我能找到的每个例子都显示如何采取来自控制器的逻辑服务,但不是如何反馈错误/异常。



我尝试过:



我尝试过使用参数的东西,但接缝非常'hacky'。

和特殊的返回代码,但是不可维护系统增长。

I'm trying to thin down my Controllers, by using a service layer. But I can not workout or find an example of how to handle issues that arise in the service layer.

As an example, I have a controller action Add Item, which has a name and user defined ID.

The code must be unique in the database.

So my controller simply takes the viewmodel and passes it to ItemService.Add()
Inside of Add is the logic to check if the ID exists. If it doesn't the controller needs to send that information back to the user and get them to change their input.

So how do I send that info back to the controller so the error message is stored and the correct view is displayed?

Is there a standard way of doing this, nearly every example I can find shows how to take the logic from the controller a service, but not how to feed errors / exceptions back in.

What I have tried:

I've tried things using out parameters but that seams very 'hacky'.
And special return codes, but that won't be maintainable as the system grows.

推荐答案

它通常由返回类型完成。如果它不起作用,则从Add方法返回false并向用户显示通用消息,或者返回带有Succeeded,DuplicateID,InvalidData等值的枚举,以指定失败的具体原因和然后,控制器将根据该消息向用户显示消息。
It's generally done by return types. Either return false from your Add method if it didn't work and show a generic message to the user, or return an enum with values like "Succeeded", "DuplicateID", "InvalidData" etc to specify the specific reason for failure and the controller will then show a message to the user based on that.


这篇关于.net核心MVC瘦控制器 - 服务层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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