Question

I am playing with WebApi2 and came across an odd issue.

I have updated the default ValuesController to use IHttpActionResult

like

    public class ValuesController : ApiController
{
    // GET api/values
    [HttpGet]
    public IHttpActionResult Get()
    {
        return Ok(new string[] { "value1", "value2" });
    }

    // GET api/values/get2
    [HttpGet]
    public IHttpActionResult Get2()
    {
        return Ok(new string[] { "value1", "value2" });
    }

When I try call Get() within postman I get an error

{ "Message": "An error has occurred.", "ExceptionMessage": "Multiple actions were found that match the request: \r\nSystem.Web.Http.IHttpActionResult Get() on type WebApplication1.Controllers.ValuesController\r\nSystem.Web.Http.IHttpActionResult Get2() on type WebApplication1.Controllers.ValuesController", "ExceptionType": "System.InvalidOperationException", "StackTrace": " at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()" }

Do I need to manually create a route for each to get this to work?

Something so simple, yet causing me a headache!

Was it helpful?

Solution

It's because you have two GET requests which take no parameters so WebApi has no way of differentiating between the two. One way would be to set up different routes for each method as you say. The easiest way to get around this though is to use the Attribute Routing library which allows you to define different routes at the Controller and Action levels really simply like this:

[RoutePrefix("api/values")]
public class ValuesController : ApiController
{   
    [GET("Get")]
    public IHttpActionResult Get()
    {
        return Ok(new string[] { "value1", "value2" });
    }

    [GET("Get2")]
    public IHttpActionResult Get2()
    {
        return Ok(new string[] { "value1", "value2" });
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top