stkxchng stkxchng - 5 days ago 5
C# Question

Web API Controller - 'action' parameter in query string

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.

Answer

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}";
    }
}
Comments