Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API routing issue

I have a VideoController and inside of it there are 2 methods like the following:

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

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

The WebApiConfig.cs is like the following:

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 method, the other one works, like if you totally comment out the 1st one, the 2nd method works, but both doesn't work when implemented. I used an Empty Web API template.

So any thoughts regarding why this is happening would be great.

like image 650
user3036757 Avatar asked Mar 16 '26 10:03

user3036757


1 Answers

You have to enable the attribute routing calling MapHttpAttributeRoutes during configuration.

Example:

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

I've tested it and worked for me correctly:

http://localhostapi/Video/1  // goes for the first method
http://localhostapi/Video/foo  // goes for the second method
like image 95
Xavier Egea Avatar answered Mar 18 '26 23:03

Xavier Egea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!