Search code examples
jqueryajaxasp.net-web-api-routing

Calling Web API Methods


I am trying to call the DataByLocation with parameter but its calling DataByLocation function with no parameter. Am I missing something? Below is the code. Thanks in advance.

Js Code

 getData:function(){
        var _data = {_location:'ABC'};
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: 'ABService/api/ABService/DataByLocation',
            data: JSON.stringify(_data),
            success: this.receivedData                
        });
    }

Controller Code

[HttpPost]
public string DataByLocation(string _location)
{
    return _location;
}
[HttpPost]
public string DataByLocation()
{

    return "no parameter";
}

Config Code

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

Solution

  • Your route api/{controller}/{id} specifies the parameter name to be "id".

    So say you have a Web Api Controller like one below

    public class AbcApiController : ApiController
    {
        public Something Get(string searchTerm)
        {
            return ...;
        }
    }
    

    and if you try to access /api/AbcApi/get/hello where hello is the search term you pass. It wont work because this route will search of Get action with a parameter id.

    Instead what will work for you, if you do not want to change your route is this

    /api/AbcApi/get?searchTerm=hello

    Plus if you are interested in learning more about web api routing, I would recommend you to read this post - Web Api Routing for multiple Get methods in ASP.NET MVC 4