Reputation: 47772
I am working on a Web Api 2 project and I am using attribute based routing. Here is a sample route:
[Route("{id:int}", Name = "GetEmployeeById")]
[HttpGet]
public IHttpActionResult GetEmployee(int id)
{
...
}
This works with the following URLs:
What I would prefer is that the first form (the parameter in the URI), would not be allowed, and only the second form (query string) would work.
Mostly, I've tried searching the web for a way to make this work, and I'm not finding much.
This page talks about route constraints but this syntax doesn't seem to work (anymore?).
This page doesn't actually prevent the URI form from working.
Upvotes: 0
Views: 1147
Reputation: 4130
There is an attribute called "[FromUri]" that you can use to decorate a method parameter, and the model binder will try to look for that parameter from the Querystring, it may not help you with this scenario but it is good to know about it, so in case you want to pass a search options for example to a Get method.
Hope that helps.
Upvotes: 1
Reputation: 47772
Actually, I was wrong about my original code. The query string parameter did not work with the route I specified. Instead, I could do this:
[Route("", Name = "GetEmployeeById")]
[HttpGet]
public IHttpActionResult GetEmployee(int id)
{
...
}
And this will do what I want. It must be getting the name id
from the function's parameter list.
Unfortunately, this means I can't put a constraint on it anymore, but I guess I can just validate within the function.
Upvotes: 0
Reputation: 869
Couple of ways to achieve this. Here are some options
Change the default routing configuration in WebApiConfig:
//Default configuration, you can see here the "id" parameter which enables action/id matching
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//It should look like this
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}"
);
Also you can do it with custom attributes.
Upvotes: 0