0

The following works:

 public class UsageController : ApiController
 {
     public int GetMilk(string param1, string param2)
     {
        return -1;
     }

     public string GetBilling(string param1)
     {
        return null;
     }
}

But the following throws a "Multiple actions were found that match the request" Exception?!?!

 public class UsageController : ApiController
 {
     public int GetMilk(MilkVM vm)
     {
        return -1;
     }

     public string GetBilling(BillingVM vm)
     {
        return null;
     }
}

How can I fix this?

Robert Christ
  • 1,910
  • 2
  • 13
  • 19

1 Answers1

0

By default, ASP.NET Web API selects an action method based on the HTTP verb and the action method parameters. In the second case, you have two action methods that can handle GET and they have one parameter each. When Web API tries to find an action method (more info here) for your GET, it will find both the methods.

You can follow RPC-style URI if you must have action methods like these. Add a mapping in WebApiConfig.cs like this.

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: "RpcStyle",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

Then, make GET to URIs with action methods like so: http://localhost:port/api/usage/getmilk?a=1&b=2.

BTW, your action methods will not be able to bind the query string to a complex type by default. Use FromUri attribute like this: public int GetMilk([FromUri]MilkVM vm). GET requests must not have a request body and hence complex types will not be bound by default.

  • This doesn't work for me. Normally, I'd do exactly what you suggest. However, in this particular case, I'm attempting to refactor an application put together by an individual who had clearly never used WebAPI before. As a result, the client desires for model binding in the controllers (BillingVM, MilkVM), but I can't change the urls for each of the actions, as there is too much code already written dependent on these endpoints. – Robert Christ Jul 01 '13 at 05:30