Srini Srini - 3 months ago 6
AngularJS Question

Not hitting with Web API two different GET methods

Implemented webapi routing and having two different route methods for for retrieving values but it is differentiated by supplying parameter type.

Api methods are getting hit for the corresponding action methods if we simply specify "apiurl/api/contact/search/sri" and "apiurl/api/contact/get/2" in direct browser url.

But when comes to communicate with angular to webapi, api is not getting hit.



//angular service

contact.search = function (inputName) {
return $http({
method: 'GET',
url: url + 'api/contact/search',
//params: { name: inputName }
data: { name: inputName }
});
//return $http.get(url + 'api/contact/search', name);
}





//WebAPI

[HttpGet]
[Route("search/{name:alpha}")]
public IHttpActionResult GetContacts([FromBody]string name)
{
repository = new ContactRepository();
if (string.IsNullOrEmpty(name))
{
var message = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Search Name can not be empty")
};
throw new HttpResponseException(message);
}
return Ok(repository.GetContact(name));
}

// GET api/contact/5
[HttpGet]
[Route("get/{id:int}")]
public IHttpActionResult Get(int id)
{
repository = new ContactRepository();
if (id == 0)
{
var message = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("Issue with Passed Id Parameter.") };
throw new HttpResponseException(message);
}
return Ok(repository.GetContact(id));
}

Answer

When you use data: { name: inputName }, it is appended to the url in the following way:

...api/contact/search?name=inputName

but what you want is this:

...api/contact/search/inputName

So, you have two options.

Either change your angular code:

return $http({
     method: 'GET',
     url: url + 'api/contact/search/' + inputName,
});

or change your API to accept QUERY params.

Hope it helps

Comments