每个资源的单个 Web API 控制器还是具有更多自定义操作的更少控制器? [英] Single Web API controller per resource or less controllers with more custom actions?

查看:20
本文介绍了每个资源的单个 Web API 控制器还是具有更多自定义操作的更少控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的大部分业务层方法公开给 Web API 项目,以允许更广泛的使用.

I want to expose most of my business layer methods to a Web API project to allow for broader consumption.

一个想法是为每个资源配备一个 Web API 控制器.

One idea is to have one Web API controller per resource.

另一个想法是每个逻辑业务部分有一个控制器,并使用属性路由来公开相关方法.

The other idea is to have one controller per logical business part and use attribute routing to expose the relative methods.

我喜欢第二种方法,它可以减少控制器.

I like the second approach, that results to less controllers.

每个资源没有一个控制器的缺点是什么?

What are the disadvantages of NOT having one controller per resource?

附加信息:

此 API 将存在于内部网中,并将为需要来自我们 2-3 个主应用程序(ERP、工资单、条形码等)的数据的支持应用程序提供服务

This API will live in an intranet and will serve support applications that need data from our 2-3 master applications (ERP,Payroll,Barcode e.t.c)

此 API 的资源将是在我们的业务层程序集中定义的业务实体.它们将是简单的对象和复杂的对象.示例:

A resource for this APi would be business entities that are defined in our business layer assembly. They will be simple objects and complex ones. Examples:

  • 库存项目
  • 客户
  • 每位客户的商品
  • 当前加载的拣货单
  • 目前的生产数据

e.t.c

示例:

我想公开诸如 GetCustomerListByAreaGetItemsListPerCategory 之类的方法.

I want to expose methods like GetCustomerListByArea or GetItemsListPerCategory.

然后呢?我应该创建另一个控制器还是使用自定义控制器操作和属性路由并将其放入现有控制器中?

What then? Should i create another controller or use custom controller actions and attribute routing and put it in the existing controllers?

包含更多信息的链接:

REST与 ASP.NET Web API 中的 RPC 比较?谁在乎;它两者兼而有之.

很好的,相当古老的文章,解释了我的问题.但实际上并没有更深入地说明如何组织控制器.在地区?还是只是文件夹?

Very nice , rather old, article explaining my question. But it does not go deeper in actual saying how to orginize controllers. In areas? Or just folders?

推荐答案

这归结为一个简单的设计原则 - 关注点分离 (SoC),您应该考虑要从业务层公开哪些功能以及基于此创建控制器.

This boils down to a simple design principle - separation of concerns (SoC), you should have a think about what functionality from your business layer you want to expose and create controllers based on that.

根据上面的示例,您可能创建一个 ProductControllerCustomerController,它们可以公开以下端点:

From your example above, you might create a ProductController and CustomerController, which could expose the following endpoints:

GET /api/customer/1234        # gets customer by id
POST /api/customer/create     # creates a new customer
GET /api/customer/1234/items  # gets all items for a customer
GET /api/product/9876         # gets a product by id
POST /api/product/create      # creates a new product

希望有帮助...

这篇关于每个资源的单个 Web API 控制器还是具有更多自定义操作的更少控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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