Building a WebAPI route in Orchard
There’s a number of differences between regular MVC controllers and WebAPI controllers that make the latter much more suitable to building APIs: they are REST-centric, they can negotiate the format of the answer, etc. Implementing WebAPI controllers in Orchard is really simple. First, you need a route, and that will be the subject of this post.
You can add your own routes, by implementing IHttpRouteProvider, like this one:
public class DeploymentApiRoutes : IHttpRouteProvider {
public void GetRoutes(ICollection<RouteDescriptor> routes) {
foreach (var routeDescriptor in GetRoutes()) {
routes.Add(routeDescriptor);
}
}
public IEnumerable<RouteDescriptor> GetRoutes() {
return new[] {
new HttpRouteDescriptor {
Priority = 5,
RouteTemplate = "api/deployment/{controller}/{action}/{id}",
Defaults = new {
area = "Orchard.ImportExport",
id = RouteParameter.Optional
}
}
};
}
}
The interface looks very much like the regular IRouteProvider, except that it uses HttpRouteDescriptors instead of RouteDescriptors. In fact, the two APIs are so close that it’s usually a safe bet to just stick Http in front of a class name to find its WebAPI equivalent.
You usually won’t have to create your own routes however: Orchard will scan modules for WebAPI controllers and generate routes for each of them. This work is done in Orchard.WebApi.Routes.StandardExtensionHttpRouteProvider. As you may have guessed, the work done by this class is very similar to what another class does for regular controllers: StandardExtensionRouteProvider. The routes generated by the WebAPI route provider are of the form:
api/{module.name}/{controller}/{id}
Without the DeploymentApiRoutes above, the same actions would be under api/Orchard.ImportExport/{controller}/{id} instead of api/deployment/{controller}/{id}.
In the next post, I’ll show how to write WebAPI actions to put behind these routes.