简体   繁体   中英

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.

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

Change your routeTemplate from

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

to

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

So you'd call something like api/Video/GetVideoByTitle/x or api/Video/GetVideoByID/x

You may want to read this, under Routing Variations > Routing by Action Name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM