Reputation: 2175
Hi I am developing web api application with angularjs. I have GET three methods in one controller and none of them are calling. For example,
public class usersController : ApiController
{
//First Get method.
[HttpGet]
[SuperAdmin]
[LoginCheck]
[ActionName("me")]
public HttpResponseMessage me()
{
}
//second Get method.
[LoginCheck]
[SuperAdmin]
public IHttpActionResult Get(int id)
{
}
//third Get method.
[HttpGet]
[LoginCheck]
[SuperAdmin]
public HttpResponseMessage Get(string role)
{
}
I am calling using below code.
this.getSubs = function () {
var role = "SUPER_ADMIN";
//role is optional here
var url = '/api/users/' + role;
return $http.get(url).then(function (response) {
return response.data;
});
}
this.getcurrentuser = function () {
var url = '/api/users/me/';
return $http.get(url).then(function (response) {
return response.data;
});
}
this.getSubsbyID = function (id) {
var url = '/api/users/' + id;
return $http.get(url).then(function (response) {
return response.data;
});
}
My routing is as follows.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I am not able to call any of three methods using angularjs. May i know where i am doing routing wrong? Any help would be appreciated. Thank you
Upvotes: 0
Views: 1571
Reputation: 1809
Two things one is this might be a problem with your requests being a CORS request. You may need to enable CORS. First you would want to install the nuget package Microsoft.AspNet.WebApi.Cors and then you would add to your api config file before your routing calls.
config.EnableCors();
Second it might be helpful to adjust your routing to use attribute routing. WebApi doesn't support Action routing like a normal MVC controller might. You might have some routing already setup in your config file, something like
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
This would allow you to call the controller users but I find it problematic trying to get an ApiController to call the appropriate GET method using the signature. I would recommend you use attribute routing. If it's not already there you can add attribute routing to your config
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Then you can setup your HttpGet attribute routing like so.
public class usersController : ApiController
{
//First Get method.
[HttpGet]
[SuperAdmin]
[LoginCheck]
[Route("api/users/me")] // this is your routing attribute
public HttpResponseMessage me()
{
}
//second Get method.
[LoginCheck]
[SuperAdmin]
[Route("api/users/{id:int}")]
public IHttpActionResult Get(int id)
{
}
//third Get method.
[HttpGet]
[LoginCheck]
[SuperAdmin]
[Route("api/users/{role}")]
public HttpResponseMessage Get(string role)
{
}
Hope this helps.
Upvotes: 1