Reputation: 9305
I have a web api with the following routes:
routes.MapHttpRoute(
name: "DefaultGet",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "Home", id = RouteParameter.Optional }
);
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = RouteParameter.Optional }
);
These are two Actions inside a Controller:
public class UserController {
public HttpResponseMessage Get(int id) {}
public HttpRespnseMesseage GetDetails(int id) {}
}
The first route allows me to access the Get()
-Method by "/api/User/4711
" The second route allows me to access the GetDetails()
-Method by "/api/User/GetDetails/4711
"
This works.
But in addition, the Get()
-Method can also be called by "/api/User/Get/4711
" (and is listed in the automaticly generated documentation, too)
How can I make sure, that I can access the Get-Method by "/api/User/4711
", but not by "/api/User/Get/4711
"?
Note: I want to keep the default routes and do not want a solution that can only be achieved by removing my default routes and using route attributes instead
Upvotes: 0
Views: 560
Reputation: 39055
You're doing something quite strange: you're mixing up deafault RESTful style routing, with action based routing.
With your current configuraton, your second route will match any ULR like /api/User/XXX/4711
where XXX
is anything. No matter if XXX
is Get
or anything else.
The only thing that you can do to avoid the second route to accept anything is to use route constraints. But, to do so, you must have a fixed set of rules. For example, if you only want to exclude Get
you can do that with a regex constraint. But if you don't know the rules, of course, you cannot implement it.
As the OP finally decided himself, if you're using a RESTful API routing style it's much better to use routing attributes, available since Wep API v2. (In fact there was a Nuget package to support it on previous versions).
Upvotes: 1