在 ASP.NET MVC 中重用 API 的 ViewModel?

发布于 2024-10-07 07:36:50 字数 410 浏览 0 评论 0原文

我想为大型 ASP.NET MVC 应用程序创建一个 API。该应用程序的所有视图都使用强类型视图模型。 API 最重要的工作是在其他平台(例如 iPhone 的 Objective C)上启用网站的功能。

现在的想法是从一开始就重用 API 的 ViewModel 和现有控制器操作,这样视图模型由控制器而不是视图作为 JSON 或 Ajax 结果返回。

但对此已经有一些讨论,因为视图模型有很多复合信息,这些信息似乎对 API 来说并不总是有用。例如,典型的 API 函数可以是 GetRanking()。属于 Ranking() 操作的视图模型实际上有更多数据,例如当前用户的名称,也许还有一些有关排名的解释。

所以问题是,解决这个问题的最佳方法是什么:为 api 编写单独的操作并返回序列化的域对象,或者重用当前的操作和视图模型,并忽略不需要的数据?

I want to create an API for a large ASP.NET MVC application. This application uses strongly typed viewmodels for all its views. The most important job for the API will be to enable the website's functionality on other platforms such as iPhone's Objective C.

Now the idea has been from the start to reuse the ViewModels and existing controller actions for the API, in such a way that the viewmodels are returned as JSON or Ajax results by the controller instead of the view.

But there has been some discussion about this, because viewmodels have a lot of composite information that does not always seem useful for an API. For example, a typical API function could be GetRanking(). The viewmodel belonging to the Ranking() action actually has more data, such as the name of the current user and maybe some explanation about the ranking.

So the question is, what would be the best way to approach this: write separate actions for the api and return serialized domain objects, or reuse the current actions and viewmodels, and just ignore the unneeded data?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

慵挽 2024-10-14 07:36:50

或者第三种选择:创建一组服务模型。从长远来看,制作单独的 ViewModel 的最大胜利往往是视图和实体可以独立更改。服务还具有一些独特的维度(例如版本控制),您可能不需要在其他地方考虑这些维度。无论如何,服务几乎总是值得有一个自己的模型。

现在,您经常会争辩说,ViewModel 可以从服务模型派生/利用服务模型来实现其角色的数据传输方面。特别是对于与用户界面无关的更新。

Or third option: create a set of service models. Long-term, the big win in making separate ViewModels tends to be the view and the entities can change independently. Services also have a few unique dimensions -- such as versioning -- that you might not need to account for elsewhere. In any case, service almost always deserves a model in and of it's own.

Now, you can often argue that the ViewModels could descend from/make use of the service models for the data transfer side of their role. Especially for updates which tends to be a bit ui agnostic.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文