mohsinali1317
mohsinali1317

Reputation: 4425

Web api 2 same method name and same parameter name

I have two methods in my api controller with same name and same number of parameters but the type of one of the parameter is different. You can see here

[HttpGet]
public dynamic Add(String organizationId, Driving driving)

[HttpGet]
public dynamic Add(String organizationId, bool driving)

I am trying to call the api like this

var data {organizationId: "something", driving: true };

var ajaxConfig = {
        url: some url,
        type: "GET",
        dataType: 'json',
        crossDomain: true,
        success: function (data) {
            onDone();
            callback(data);
        },
        error: function (error, textStatus, errorThrown) {
        }

      };
        ajaxConfig.data = data;

    $.ajax(ajaxConfig);

The system gets confused between which api to call. Am I doing it wrong? Is there some other way to do it?

Upvotes: 1

Views: 8299

Answers (2)

John Verbiest
John Verbiest

Reputation: 349

The controller can only make the difference between two identically named methods in two ways:

  • Via HttpVerb attributes: In this case you could apply [HttpGet] to the first method and [HttpPost] to the second. When calling from a client you must use the Get method when using the first one and the Post method when using the second one.
  • Via Route attribute: In this case you tell MVC what route to take for each method (ex: [Route("api/mycontroller/AddWithBoolean")] ). In this case the client chooses the correct method by using the correct route.

In case you dont want to make the distinction in the client and you want your server to do the distinction you need another approach.

You can create a method like this:

[HttpGet]
public dynamic Add(String organizationId, object driving)
{
     if (driving is Driving)
          // execute code
     else
          // execute other code
}

This example is far from complete but it could be an approach.

With regards, John

Upvotes: 1

Marcus Höglund
Marcus Höglund

Reputation: 16846

You could use attribute routing to make the methods point to different routes in the controller

[HttpGet]
[Route("api/controller/add1")] // Url http://url.domain.com/api/controller/add1
public dynamic Add(String organizationId, Driving driving)

[HttpGet]
[Route("api/controller/add2")] // Url http://url.domain.com/api/controller/add2
public dynamic Add(String organizationId, bool driving)

Upvotes: 3

Related Questions