2

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?

4

2 回答 2

1

为避免这种情况,我添加了一个签入AuthorizationFilterAttribute以拒绝此类请求。

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");
    }
}
于 2017-07-19T09:50:15.923 回答
0

尝试将参数名称“id=3”改为“anotherId=3”

于 2013-10-25T15:53:04.900 回答