Web API routing problem

I have a VideoController and inside it there are two methods:

[Route("api/Video/{id:int}")]     
public Video GetVideoByID(int id){ do something}    

[Route("api/Video/{id}")]    
public Video GetVideoByTitle(string id) {do something}

      

WebApiConfig.cs looks like this:

public const string DEFAULT_ROUTE_NAME = "MyDefaultRoute";
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: DEFAULT_ROUTE_NAME,
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }
}

      

So when I comment out any of the methods, the other works, for example if you comment out the first completely, the second method works, but both of them fail when implemented. I used the Empty Web API pattern.

So, any thoughts on why this is happening would be great.

+3


source to share


2 answers


You must activate attribute routing calling MapHttpAttributeRoutes during configuration.

Example:

public static void Register(HttpConfiguration config)
{
    // Web API routes
    config.MapHttpAttributeRoutes();
    ...
}

      



I tested it and it worked correctly for me:

http://localhostapi/Video/1  // goes for the first method
http://localhostapi/Video/foo  // goes for the second method

      

+4


source


Change routeTemplate

from

routeTemplate: "api/{controller}/{id}",

      

to



routeTemplate: "api/{controller}/{action}/{id}",

      

So, you would call something like api/Video/GetVideoByTitle/x

orapi/Video/GetVideoByID/x

You can read this under Routing Options> Routing By Action Name

+1


source







All Articles