0

I have a couple of post methods in my controller. Whenever I post data to this controller, only the first POST method is called. My requirement is to call the second method as the parameters are going to be different for both the methods. Here is the route config:

config.Routes.MapHttpRoute(
name: "AddUser",
routeTemplate: "api/users/adduser",
defaults: new { controller = "users" }
);
config.Routes.MapHttpRoute(
name: "ChangeUser",
routeTemplate: "api/users/changeuser",
defaults: new { controller = "users" }
);

This is my controller's code:

[AllowAnonymous]
[ActionName("adduser")]
public string PostDetails(JObject userData)//Always this method is called.
{
//My code here
}

[AllowAnonymous]
[ActionName("changeuser")]
public string ChangeUser(int userId)
{
//My code here
}

This is called from the view:

Ext.Ajax.request( { url: 'localhost/myapp/api/users/changeuser'
                  , mode: 'POST'
                  , params: { userID: 1 }
                  }
                );
user1640256
  • 1,691
  • 7
  • 25
  • 48

2 Answers2

1

Adding constrains in the route config will solve your problem. Try below config..

config.Routes.MapHttpRoute(
name: "AddUser",
routeTemplate: "api/{controller}/{action}",
defaults: new { },
constraints: new { controller = "users", action = "adduser" }
);

config.Routes.MapHttpRoute(
name: "ChangeUser",
routeTemplate: "api/{controller}/{action}",
defaults: new { },
constraints: new { controller = "users", action = "changeuser" }
);

The C# part:

[AllowAnonymous]
[ActionName("adduser")]
[AcceptVerbs("Post")]
public string PostDetails(JObject userData)//Always this method is called.
{
//My code here
}

[AllowAnonymous]
[ActionName("changeuser")]
[AcceptVerbs("Post")]
public string ChangeUser(int userId)
{
//My code here
}
petchirajan
  • 4,152
  • 1
  • 18
  • 20
  • Didn't work. Still "AddUser" method is getting called. – user1640256 Mar 25 '14 at 09:22
  • I updated the C# code part also. The route template string must be exactly "api/{controller}/{action}". Don't use the controller name or action name in the route template. The constraints will check for the controller and action from the given url.. – petchirajan Mar 25 '14 at 10:21
  • I changed it as per the code provided but now if I call the controller as "localhost/myapp/api/users", it goes to the same method(the first post method). If I call the controller as "localhost/myapp/api/users/changeuser", it gives 404 error. – user1640256 Mar 25 '14 at 11:08
  • I think the problem is your changeuser method. it accepts integer as a parameter. you have to modified it to the value type. create one class which contains one integer property, and use that class as a parameter. refrer: http://stackoverflow.com/questions/16374954/passing-array-of-integers-to-webapi-method – petchirajan Mar 25 '14 at 11:35
0

Try:

[HttpPost, ActionName("Name")] 

instead of:

[ActionName("Name")]

I'm not an expert but it might work this way.

Maratto
  • 162
  • 1
  • 12