Search code examples
c#.netasp.net-web-apiasp.net-web-api-routing

Same method signature for two diff methods in web api


it might have duplicate but i didn't find right solution,

My web api,

public class SampleController : ApiController
{
    public string Get(int id)
    {
        return "value";
    }

    public string hello(int id)
    {
        return "value";
    }
} 

my webapiconfig,

config.Routes.MapHttpRoute(
           name: "DefaultApi",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional }
       );

my problem is

When i call http://localhost:1234/api/Sample/5 it's hitting Get(int id) but how can i call method 2 i.e hello(int id) ?? what needs to be changed and what's the best way to handle these kind of scenarios ??


Solution

  • TLDR:

    If you want to reference individual actions in your Web API then change your routing to this:

    routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );
    

    Then you can access your action like this: localhost/api/{controller}/{action}/. Look here for further information, especially "Routing by Action Name".

    Orig:

    You seem to expect the same behaviour as with MVC Controllers. The Standard-Routing for MVC-Controller is this:

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

    This corresponds to the name of the controller, the method which is to be used and some form of input. ApiControllers Route differently:

    routeTemplate: "staticPart/{controller}/{id}"
    

    As you can see there is only a reference to the individual controller and the input, as well as the "staticPart" which normally is something like /api/

    The Idea is that you use a RESTful approach, connecting methods with different types of http methods (eg. DELETE, GET, POST, PUSH and PUT)

    The Get Method in your example is a special because through the name "Get" you have told the compiler that this method corresponds with HTTP-GET.

    So to get to your question: Either you change your Routing to that of MVC-Controller. So that you reference individual actions in your requests or you use different HTTP-Methods. Or you set routes indivdually as shown by MaxB

    You can find an official overview on Web API routing here There you'll find examples on all possibilities.