4
votes

I have following Web api controller

public class ApiController : Controller
{
    [Route("api/test")]
    [HttpGet]
    public string GetData(string key, string action, long id)
    {
        var actionFromQuery = Request.Query["action"];
        return $"{key} {action} {id}";
    }
}

I need a parameter named 'action' in query string so it is backwards compatible with existing API.
When I make a get request, action method parameter gets incorrectly assigned to web api action == controller method name.

Example GET
http://SERVER_IP/api/test?key=123&action=testAction&id=456
Returns "123 GetData 456"

I would expect it to return "123 testAction 456"
actionFromQuery variable is correctly assigned to 'testAction'.
Is 'action' a reserved variable that cannot be overridden?
Can I fix this by changing some configuration?

I am not configuring any routes, there is only services.AddMvc(); and app.UseMvc(); in my Startup.

2
try to annotate the action parameter with [FromUri] attribute - Haitham Shaddad
Thanks, adding [FromQuery] fixed it. (Using ASP.NET Core). Add this as an answer and I will accept it. - stkxchng

2 Answers

3
votes

Resolved thanks to this comment

Adding [FromQuery] helps and the variable is correctly assigned

public class ApiController : Controller
{
    [Route("api/test")]
    [HttpGet]
    public string GetData(string key, [FromQuery] string action, long id)
    {
        return $"{key} {action} {id}";
    }
}
0
votes

In WebApi routing, the Action parameters are paired up with placeholders in the route definition, in curly braces, e.g. /api/{foobar}/{baz}.

The problem you're facing is that {controller} and {action} are "special" placeholders, reserved for the name of the Controller and Action method respectively (though the latter is usually omitted from WebApi routes).

I've not been able to find a way around it yet though :(