0
votes

In my Web API 2 project I have two POST methods:

[HttpPost]
public virtual IHttpActionResult Create([FromBody]TDto value) { ... }

[Route("many")]
[HttpPost]
public virtual void CreateMany([FromBody]TDto[] value) { ... }

My route template looks like this:

config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}")

When I make a POST to http://server/api/Products I get the following error: "Multiple actions were found that match the request: Create on type ProductsController, CreateMany on type ProductsController"

Why does the method with the RouteAttribute set to "many" match the route? Shouldn't "many" be a mandatory part of the URL?

When I post to http://server/api/Products/many the correct method is called.

I know I can get around the problem by specifying the Order in the Route-attribute, but I want to understand why this is happening.

Edit:
Just found out that if I added an empty route to the Create-method, it works as I want:

[Route("")] // <-- ADDED THIS
[HttpPost]
public virtual IHttpActionResult Create([FromBody]TDto value) { ... }

[Route("many")]
[HttpPost]
public virtual void CreateMany([FromBody]TDto[] value) { ... }

If anyone can explain why this is happening I'm still all ears :-)

1

1 Answers

0
votes

OK, maybe this wasn't so strange after all...

In my original setup this is what happens:

  • When doing a POST to http://server/api/Products/many it matches the second method by its RouteAttribute. No need to check the "DefaultApi"-routing. So that worked.
  • When doing a POST to http://server/api/Products it does not match any RouteAttribute route so instead it checks the "DefaultApi"-routing andboth methods match the route in config. I get the "Multiple actions..."-exception.

After adding [Route("")] to the first method this is what happens:

I think I believed that the RouteAttribute disabled the "DefaultApi"-route for that method. That was obviously not the case.