Reputation: 957
I have more or less standard route for webapi (except I added {action}):
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{action}",
defaults: new { id = RouteParameter.Optional, action = RouteParameter.Optional }
);
The problem starts when I have a controller, that should accept any (zero or more, with random names) query parameters. Say it works with GET HTTP to URL like:
/api/Data/2836581?id=3&name=lol&etc=23&filter=all_but_nice
In the Get(int id) controller method I receive id==3, while I expected id==2836581.
I can bypass this using:
Request.GetRouteData().Values["id"]; // 2836581
Request.GetQueryNameValuePairs(); // All query parameters
But this solutions feels more like a HACK rather than "happy-path".
Can I make WebApi prioritize route variables over url-query params?
Upvotes: 2
Views: 1501
Reputation: 11
To avoid this I add a check in AuthorizationFilterAttribute
to reject this sort of request.
private static void dedupQuery( HttpActionContext actionContext)
{
var routeData = actionContext.Request.GetRouteData().Values;
var queryString = actionContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
if( queryString.Keys.Any(s => routeData.Keys.Contains(s)))
{
throw new HttpException((int)HttpStatusCode.Conflict, "DUPLICATED PARAM");
}
}
Upvotes: 1