Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

c# - Single Web API controller per resource or less controllers with more custom actions?

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

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?

Additional Info:

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)

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:

  • Inventory Items
  • Customers
  • Items per Customer
  • Current loading pickslips
  • Present production data

e.t.c

Example:

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?

A link with some more info:

REST vs. RPC in ASP.NET Web API? Who cares; it does both.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

Hope that helps...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...