I have 2 API routes for my API atm, but I want to add more, and the way I am doing it it seems to overwrite each other, so in the code I pasted, only the CreateUser
route works.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "CreateUser",
routeTemplate: "api/{controller}/{cUser}",
defaults: new
{
controller = "User",
action = "CreateUser",
cUser = RouteParameter.Optional
});
routes.MapHttpRoute(
name: "AllGames",
routeTemplate: "api/{controller}/{playerId}",
defaults: new
{
controller = "Game",
action = "GetAllGames",
playerId = RouteParameter.Optional
});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
}
Web API Controller is similar to ASP.NET MVC controller. It handles incoming HTTP requests and send response back to the caller. Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder.
If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.
MapHttpAttributeRoutes() enables attribute routing which we will learn later in this section. The config. Routes is a route table or route collection of type HttpRouteCollection. The "DefaultApi" route is added in the route table using MapHttpRoute() extension method.
I believe the pattern api/{controller}/{cUser}
in "CreateUser" route is matching with rest of the controller actions because of its more generic pattern. Use specific controller name in the routes as "User" (api/User/{cUser}) and "Game" (api/Game/{playerId}). The more specific routes should be at the top and more generic at the bottom.
routes.MapHttpRoute(
name: "CreateUser",
routeTemplate: "api/User/{cUser}",
defaults: new
{
controller = "User",
action = "CreateUser",
cUser = RouteParameter.Optional
}
);
routes.MapHttpRoute(
name: "AllGames",
routeTemplate: "api/Game/{playerId}",
defaults: new
{
controller = "Game",
action = "GetAllGames",
playerId = RouteParameter.Optional
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With