Chris Baxter
Chris Baxter

Reputation: 16373

How to design for non-CRUD operations in MVC4's Web API?

I am starting a new project using ASP.NET MVC4 and Visual Studio 2012. In terms of API design, most examples focus on basic CRUD operations via PUT, GET, POST and DELETE verbs on entities (as you would expect). I was reading the following:

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

The article suggests that if I choose to map a route as

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}/{action}",
    defaults: new { action = RouteParameter.Optional }
);

This is more of an RPC style approach; from which I inferred they are recommending two routes with two controllers to split up each operation:

Perhaps something like for parent entity CRUD:

routes.MapHttpRoute(
    name: "Parent",
    routeTemplate: "api/{controller}/{id}/{action}",
    defaults: new { id = RouteParameter.Optional }
);

and for child entity CRUD:

routes.MapHttpRoute(
    name: "Child",
    routeTemplate: "api/user/{id}/{controller}",
    defaults: new { id = RouteParameter.Optional }
);

From a data/crud perspective this makes total sense. However, what about when you want to perform a non-crud operation on an entity (i.e., /User/NoahBawdy/SignIn or /User/NoahBawdy/ChangePassword)? I could see these being a PUT or POST action, but does it really require it's own controller? Is this the wrong way to approach the API design for these types of operations?

Any insight greatly appreciated as always.

Upvotes: 2

Views: 2375

Answers (1)

Bah
Bah

Reputation: 111

You raised some interesting points in your post. I was faced with a similar challenge on a project I am working on and my approach is to add an action parameter on the routing configuration.

With that change i could add any method to the controller and call it from the client. This avoids the need to specify multiple controllers for methods that conceptually belongs in the same controller.

Omar

Upvotes: 3

Related Questions