2

I am using asp.net mvc5 and webapi 2. Here is my sample controller -

public class DataFetchController : ApiController { public async Task<HttpResponseMessage> GetDO() { return Request.CreateResponse("ok"); } public async Task<HttpResponseMessage> GetDoes() { return Request.CreateResponse("ok"); } } 

In my WebApiConfig.cs file I have the following code -

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

When I run this project and try to browse "api/DataFetch/getdo" link then i encountered an error that shows -

{"$id":"1","Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: \r\nGetDO on type MagicMeter.Controllers.DataFetchController\r\nGetDoes on type MagicMeter.Controllers.DataFetchController","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.d__1.MoveNext()"}

How can I fix this problem??

1
  • This is because how REST in WebApi works. You don't need to use REST as the provided answer shows (where you instead need to specify the action in the url instead of the http verb), but with the route as per the question, the action is determined by the http verb, in this case GET. As there's only one verb (GET), there's only one action which is determined automatically (or by tags) by the name "Get*". You can have multiple actions by having different overloads (eg GetAll() and Get(id)) but not if they have the same signature. Commented Aug 23, 2015 at 20:28

1 Answer 1

2

Try changing your route config code to this

 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); 
Sign up to request clarification or add additional context in comments.

3 Comments

should i add this as new routes.maphttproute or i would edit the existing one?
You can do either one. In case if you want to add this as new route, change name because DefaultAPI is already used.
It should be noted that this will mean your API is not RESTful. But as your Q already includes the action, it looks like you're not using REST, so should be ok in this case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.