Reputation: 3
I've got a problem using ASP.NET WebAPI Controller. What i try to build is a controller which contains two actions that can be called by a http-get. What i have so far:
[HttpGet]
public IList<Model> Get()
{
...
}
[HttpGet]
public IList<Model> GetAllWorkshops()
{
...
}
I also edited my RouteConfig.cs to the following:
routes.MapHttpRoute(
name: "API Default With ID",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}"
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =UrlParameter.Optional }
);
The strange behaviour is that if i call : http://localhost:1536/Api/Workshop/Get or localhost:1536/Api/Workshop/GetAllWorkshops, i get the exception that multiple actions were found that match this request. But if i call localhost:1536/Api/Workshop/Get/1 or localhost:1536/Api/Workshop/GetAllWorkshops/1 it was works perfectly. So i think that the route with the id works. But why do the other two requests throw these exceptions?
I tried almost every imaginable route. It would be great if you find my mistakes!
Thank you very much!
Upvotes: 0
Views: 931
Reputation: 9698
Because route named "API Default With ID" has id
as optional, so /api/workshop/get
matched both the first and second route, hence the error.
To fix this error, you can remove second route because it is just a subset of the first route template.
However, it is better to use new Attribute Routing introduced in Web API 2, it is by far more maintainable and easy to understand than using old-style mapping.
If you use attribute mapping, your class will look like:
[RoutePrefix("api/workshop")]
public class WorkshopController : ApiController {
[HttpGet]
[Route("Get")]
public IList<Model> Get()
{
...
}
[HttpGet]
[Route("GetAllWorkshops")]
public IList<Model> GetAllWorkshops()
{
...
}
}
Very clear and concise.
Upvotes: 1