Tuesday, June 24, 2014

Single controller with multiple GET methods in ASP.NET Web API

Problem:
Using a WebAPI pattern on a web services website, I ran into an issue.  The default WebAPI Pattern provides routing to the standard HTTP routes, GET, POST, PUSH, DELETE.  This is fine if you have no need to "overload" the routes.  My issue revolves around the need to have GET do mulitple actions besides just getting me all records or individual records.  I needed to return some attributes of the object being served up. 

Mike Wasson form MSFT has a great post on ASP.Net routing.  He describes how WebAPI has been designed.  The key was tweaking the routing table!


Solution:
I opened the WebApiConfig.cs file which is located in the App_Start directory of my WebAPI site.
The updated routing looks like

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

I have noted from some initial testing, that the routeTemplate must be unique.  I had tried using api as the common root for both routing entries.  The issue was that at runtime the routing always defaulted to the initial path.



Source:
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
http://stackoverflow.com/questions/9499794/single-controller-with-multiple-get-methods-in-asp-net-web-api

No comments:

Post a Comment