Search code examples
c#asp.netasp.net-web-apiasp.net-core-webapiasp.net-core-2.1

ASP.NET Core Web API multiple actions with the same action verb but different signature


Let's say I have

[HttpPost]
public ActionResult<Object> Login([FromBody]LoginViewModel loginViewModel)
  {
    ....
  }

[HttpPost]
public ActionResult Logout()
  {
    ....
  }

in the same controller.

And I am getting AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:

...Login
...Logout

I can simply fix it by using the route attribute but I don't understand why core doesn't bind it. I mean the signature is different. ?


Solution

  • The routing mechanism for web api, both Core and .NET framework works the same way. First they take into account controller name, then they look for proper http method and finally they look if the query string parameters match (or parameters contained withing url specified with Route). So if your 2 actions would differ by parameters taken from url, then there is no ambiguity. Parameters carried by body are not analyzed by routing mechanism, even the fact they are or there are none. This stems from a fact that parameters coming by url are just plain strings - easy to compare against. Whereas body is a json and it is more tricky to analyze it. In fact in Login method case there is no parameter loginViewModel in the request - the whole request body gets serialized to LoginViewModel object.