Monday, April 8, 2013

Customize the ASP.NET Web API Help page with REST style groupings

If (like me) you are keeping up to speed with Microsoft's ASP.NET Web API framework you might have noticed the recent release of the ASP.NET and Web Tools 2012.2 Update. What was exciting for me in this release was the addition of an automatically generated help page which can be configured to use comments in your code for the documentation. What better way to maintain the documentation for a web service than in the code itself?

Although the display of the default help page is pretty comprehensive from the start, I wanted to change the way it grouped items to better suit my implementation of a REST service. 

During the creation of my Web API project I had considered using a separate Controller for each unique request with the 4 standard HTTP methods available (GET, POST, PUT & DELETE). In practice however it seemed neater to consider a Controller as a business entity (e.g. Customer) and to allow for several Actions types within it. This cuts down on the number of separate .cs files needed in the project and provides a logical grouping for developers trying to navigate your API e.g. 
  • Customer/Address
  • Customer/Invoices
  • etc.
In order to update the help page to group by entity/controller and then list action names and available methods I made the following changes;
  1. Areas\HelpPage\Views\Help\Index.cshtml
  2. Areas\HelpPage\Views\Help\DisplayTemplates\ApiGroup.cshtml
  3. Areas\HelpPage\HelpPage.css
1) Update the Index to include Action in the object model and then render a separate table for each Controller. The way the table is implemented in code here is pretty ugly in IMHO but I'm new to the Razor syntax and it works, so...

2) Update the rendering of the Action names to group by HTTP method and only list the action name once per url. Also add an HTTP link back to the service to allow immediate testing of GET's;

3) Beautify the CSS(!)

And that's all there is to it, a self-documenting REST style Web API service which can be maintained by developers, for developers - pretty neat!


  1. I received this error:

    {"The model item passed into the dictionary is of type 'System.Linq.Lookup`2+Grouping[System.String,System.Web.Http.Description.ApiDescription]', but this dictionary requires a model item of type 'System.Linq.IGrouping`2[System.Web.Http.Controllers.HttpControllerDescriptor,System.Web.Http.Description.ApiDescription]'."}

  2. Nevermind, apparently I missed step 2. So now that I implmented step 2, I now receive the following error:

    'System.Web.Http.Description.ApiDescription' does not contain a definition for 'GetFriendlyId' and no extension method 'GetFriendlyId' accepting a first argument of type 'System.Web.Http.Description.ApiDescription' could be found (are you missing a using directive or an assembly reference?)

  3. Nevermind again, I got it to finally work. Thanks.