4

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
  • 4
    try to annotate the action parameter with [FromUri] attribute Commented Nov 29, 2016 at 10:26
  • 2
    Thanks, adding [FromQuery] fixed it. (Using ASP.NET Core). Add this as an answer and I will accept it. Commented Nov 29, 2016 at 11:05

2 Answers 2

4

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

Comments

0

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 :(

Comments

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.