问题
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:
- ://host/employee/12345
- ://host/employee?id=12345
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.
What I've Tried
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.
回答1:
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.
- http://msdn.microsoft.com/en-us/library/system.web.http.fromuriattribute(v=vs.118).aspx
- http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
Hope that helps.
回答2:
Couple of ways to achieve this. Here are some options
- Rename parameter to something else than id (eg. employeeId).
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.
回答3:
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.
来源:https://stackoverflow.com/questions/26513942/asp-net-web-api-2-attribute-based-routing-how-do-i-force-a-parameter-to-quer