Search code examples
c#asp.netasp.net-web-apiasp.net-web-api-routing

Web API controller with two PUT methods throw an InvalidOperationException


I'm developing an ASP.NET Web Api 2.2 app with .NET Framework 4.5.1 and C#.

I have a controller with this method:

public HttpResponseMessage Get(
    string productCode,
    byte codeLevel,
    string productionOrderName,
    string batchName,
    string lineName,
    int quantity)
{

And this is how I have configured its route on WebApiConfig:

config.Routes.MapHttpRoute(
    name: "ExternalCodesActionApi",
    routeTemplate: "api/ExternalCodes/{action}/{productCode}/{codeLevel}/{productionOrderName}/{batchName}/{lineName}/{quantity}",
    defaults: new { controller = "ExternalCodes" });

But now I have another method on the same controller (ExternalCodesController):

[HttpPut]
public HttpResponseMessage SetCodesAsUsed(List<string> codes)
{

But, with that route, when I put to that method (http://myHost:53827/api/ExternalCodes/SetCodesAsUsed), I get an InvalidOperationException with the message:

"Several actions that matched the request were found:

SetCodesAsUsed in type MyProject.Web.API.Controllers.ExternalCodesController

SetCodesAsUnUsed in type MyProject.Web.API.Controllers.ExternalCodesController",

There is also another method in the same ExternalCodesController:

[HttpPut]
public HttpResponseMessage SetCodesAsUnUsed(List<string> codes)
{

What am I doing wrong?

The methods have different names.


Solution

  • The web api doesn't pay much attention to method names - it just see's two PUT's with the same signature.

    Web API 2 Attribute Routing is the most convenient solution to this issue as it makes it easy to mix RPC calls in a RESTful API

    eg:

    [HttpPut]
    [Route("api/ExternalCodes/SetCodesAsUnUsed")]
    public HttpResponseMessage SetCodesAsUnUsed(List<string> codes)
    
    [HttpPut]
    [Route("api/ExternalCodes/SetCodesAsUsed")]
    public HttpResponseMessage SetCodesAsUsed(List<string> codes)