barteloma
barteloma

Reputation: 6875

Web Api Multiple actions were found

I have actions that have different type parameters.

public class MyController : ApiController
{       
    [HttpPost]
    public UpdateFeatureResponse UpdateFeature(UpdateFeatureResuest reqResuest)
    {
        return new UpdateFeatureResponse { IsSuccess = true };
    }

    [HttpPost]
    public DeleteFeatureResponse DeleteFeature(DeleteFeatureRequest request)
    {
        return new DeleteFeatureResponse{ IsSuccess = true };
    }

}

And my request types are like this:

public class UpdateFeatureResuest
{
    public int Id { get; set; }
    public string Feature { get; set; }
}

public class UpdateFeatureResponse
{
    public bool IsSuccess { get; set; }
}

public class DeleteFeatureRequest
{
    public int Id { get; set; }
}

public class DeleteFeatureResponse
{
    public bool IsSuccess { get; set; }
}

Route is here:

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

When I send request (http://localhost:52285/api/My/UpdateFeature) via fiddler it returns HTTP/1.1 500 Internal Server Error

Error message is :

{"message":"An error has occurred.","exceptionMessage":"Multiple actions were found that match the request: \r\nUpdateFeature on type WebGUI.Controllers.MyController\r\nDeleteFeature on type WebGUI.Controllers.MyController","exceptionType":"System.InvalidOperationException","stackTrace":" .....

Upvotes: 5

Views: 1211

Answers (2)

dan
dan

Reputation: 532

Better to use Route attribute.

For example

[RoutePrefix("myapi")]
public class MyController : ApiController
{       
    [Route("update")]
    [HttpPost]
    public UpdateFeatureResponse UpdateFeature(UpdateFeatureResuest reqResuest)
    {
        return new UpdateFeatureResponse { IsSuccess = true };
    }

    [Route("delete")]
    [HttpPost]
    public DeleteFeatureResponse DeleteFeature(DeleteFeatureRequest request)
    {
        return new DeleteFeatureResponse{ IsSuccess = true };
    }

}

Now add this to your WebApiConfig before config.Routes.MapHttpRoute()

config.MapHttpAttributeRoutes();

Upvotes: 0

DavidG
DavidG

Reputation: 119146

Your route is wrong as it doesn't specify the action name so it's treating the UpdateFeature part as the ID parameter. Change it to this:

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

Upvotes: 4

Related Questions