What are the best practices for combining REST and RPC in ASP.NET Web API? Let’s first go over a couple of definitions. A REST based API exposes data as resources (or nouns) at URIs that clients interact with via HTTP verb based methods e.g. GET and POST. Remote procedure calls (RPC) are essentially endpoints that perform arbitrary actions, not necessarily tied to a particular resource e.g. SendTimesheet.
Web API automatically routes requests to API methods by convention, matching the request’s HTTP verb to a named method in your API class e.g. GetTimeSheet. This is all well and good but what happens when we want to call a method that doesn’t correspond to a verb e.g. SendTimesheet? The good news is that Web API supports RPC-style routing:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
OK great but what about the controller. Should we mix REST and RPC methods in the same controller? I initially tried this yesterday but quickly found that it was a recipe for route conflicts due to overlapping method signatures (a result of using up the HTTP verbs). In the end I created an additional controller specifically for the action based RPC methods. So I now have two controllers. One for REST methods and one for the custom actions. My WebApiConfig looks like this:
config.Routes.MapHttpRoute(
name: "rpcapi",
routeTemplate: "rpcapi/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);