Reputation: 8086
I want to create the following API:
/api/verifications/1
/api/verifications/getfoo/1
Controller methods:
public string Get(int id)
{
return "value";
}
public string GetFoo(int id)
{
return "value";
}
WebApiConfig:
config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
With such config I can access /api/verifications/getfoo/1
but the /api/verifications/1
cause an exception: Multiple actions were found that match the request.
How can I configure routes to have default Get and named Get method?
Upvotes: 1
Views: 210
Reputation: 3227
Here you're ignoring standard naming convention for action names. Usually Get
method is bound to request with no parameters to return all available items. As for me, it's better to define different certain name for each action, like GetOneKindOfThings
and GetOtherKindOfThings
to make your API more self descriptive.
Anyway you could use the following trick to let framework understand your routes correctly:
public string Get(int defaultId)
{
return "value";
}
public string GetFoo(int id)
{
return "value";
}
config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{defaultId}", new { defaultId = RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
Upvotes: 0
Reputation: 1501
I think you just need to specify the action
for the first route. e.g:
config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { action = "Get", id = RouteParameter.Optional }, new { id = @"\d+" });
Upvotes: 2