MVC4 Web API–REST Sub-resources

To create sub-resources (e.g. /books/1/authors) in the Web API that shipped with MVC beta 4, you can create a “SubResourceControllerFactory” to mangle the controller name to include a sub controller as follows:

public class SubResourceControllerFactory : DefaultHttpControllerFactory
{
    public SubResourceControllerFactory(HttpConfiguration configuration) : base(configuration)
    {
    }

    public override System.Web.Http.Controllers.IHttpController CreateController(System.Web.Http.Controllers.HttpControllerContext controllerContext, string controllerName)
    {
        if (controllerContext.RouteData.Values.ContainsKey("subcontroller"))
        {
            return base.CreateController(controllerContext, controllerName + controllerContext.RouteData.Values["subcontroller"]);
        }

        return base.CreateController(controllerContext, controllerName);
    }
}

This factory can be instantiated using a custom IDependencyResolver that’s looking for a type of IHttpControllerFactory, for example in Global.asax.cs (Application_Start):

GlobalConfiguration.Configuration.ServiceResolver.SetResolver((type) =>
    {
        if (type == typeof(IHttpControllerFactory))
        {
            return new SubResourceControllerFactory();
        }
    });

Finally you create a route similar to:

routeCollection.MapHttpRoute("SubController", "api/{controller}/{id}/{subcontroller}/{subId}", new { subId = RouteParameter.Optional })

Advertisements