I am attempting to write an API. The signatures look like this:
public class CardsController : ApiController
{
[HttpGet]
public ClientData NewGame(){...}
[HttpGet]
public ClientData Deal(int sessionId){...}
[HttpGet]
public ClientData Stand(int sessionId){...}
}
With everything else at default I was getting an error saying my class couldn’t differentiate between Deal and Stand. After a bit of research I found it was a routing issue. So I decided to update my routing.
My global.asax.cs now looks like this:
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapHttpRoute("api", "api/{controller}/{action}/{value}", new { value = RouteParameter.Optional});
}
}
Going to http://localhost:54924/api/Cards/Stand/19 gives an error that says no HttpResource was found, and going to http://localhost:54924/api/Cards/Stand triggers the NewGame() action. How can I get Stand and Deal to work on the same controller?
Add the routes:
Now, in your Controller class:
Now, whenever you pull up the url http://www.yourhost.com/api/deal/12345, the Deal function will be called. Same thing with Stand.
Keep in mind that whatever you set in your routes tables are only for recognizing whether a url is valid. By having the action specified in the third parameter, you’re telling Web Api to find a function whose ActionName attribute is set to what you specify.
Another thing – put those two routes BEFORE any of your default api routes.