简体   繁体   中英

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.

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

In WebApi routing, the Action parameters are paired up with placeholders in the route definition, in curly braces, eg /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 :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM