3

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?

2 Answers 2

2

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");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try to change the name of the parameter "id=3" to "anotherId=3"

5 Comments

Query params names are almost random. I do not have control over them.
I could rename route variable id => idAndARandomString, but what happens if I get ?idAndARandomString=12 another day?
try to change "id" to "itemid" in your rout definition: routeTemplate: "api/{controller}/{itemid}/{action}",
I don't like "renaming" solution: First, I have other controllers, where variable name "id" fits perfectly. Second, I don't have control over query-parmeters.
Unfortunately we are not always doing what we like. You have two parameters with same name. I believe that "I do not like to name different parameters with same name" goes hire in priority list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.