1

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.

3

1 Answer 1

7

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)
3
  • The route templates in this answr doesn't follow the recommended Resource Naming for RESTful Web API. (read: restapitutorial.com/lessons/restfulresourcenaming.html ) Is there a better approach?
    – Tohid
    Jan 23, 2017 at 16:31
  • According to your link's definition I think you might need to have two controllers, each with one PUT? eg: PUT /api/UnsedExternalCodes and PUT /api/UsedExternalCodes. Jan 23, 2017 at 16:57
  • Just the answer i needed.
    – nahaelem
    May 11, 2018 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.