.net核心MVC瘦控制器

编程入门 行业动态 更新时间:2024-10-28 13:21:35
本文介绍了核心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瘦控制器

本文发布于:2023-11-15 23:07:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598768.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   核心   net   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!