Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make more MapHttpRoutes for MVC 4 Api

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
        });
}
like image 417
Mech0z Avatar asked May 26 '12 12:05

Mech0z


People also ask

What is Apicontroller in Web API?

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.

What makes it different a Web API routing from MVC routing?

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.

What is MapHttpRoute?

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.


1 Answers

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
    }
);
like image 190
Abhijit-K Avatar answered Oct 02 '22 13:10

Abhijit-K