Accept multiple parameters for API in .NET Core 2.0 using attribute routing

12,895

Solution 1

Use [FromQuery] to specify the exact binding source you want to apply.

//GET api/scoInfo?activityId=1&studentId=1&timestamp=1527357844844
[HttpGet("api/scoinfo")] 
public async Task<IActionResult> GetLearningTask(
    [FromQuery]int activityId, 
    [FromQuery]int studentId, 
    [FromQuery]int timeStamp) {
    //...
}

MVC will try to bind request data to the action parameters by name. MVC will look for values for each parameter using the parameter name and the names of its public settable properties.

Reference Model Binding in ASP.NET Core

Solution 2

Query parameters are not part of the route path. The route for https://localhost:44329/api/scoInfo?activityId=1&studentId=1&timestamp=1527357844844 would be "api/scoinfo" . The handling method would then have parameters decorated with [FromUri] which will map to the values in the query parameter.

[Route("api/scoinfo")]
public HttpResponseMessage GetScoInfo([FromUri]int activityId, int studentId, int timeStamp)
Share:
12,895
Roddy Balkan
Author by

Roddy Balkan

Developer, Entrepreneur

Updated on June 09, 2022

Comments

  • Roddy Balkan
    Roddy Balkan almost 2 years

    I have an incoming GET request as follows:

    https://localhost:44329/api/scoInfo?activityId=1&studentId=1&timestamp=1527357844844
    

    How would I create an endpoint in ASP.net-core that would accept this request.

    I have tried different versions of the following and nothing works:

    [HttpGet("{activityId: int}/{studentid: int}/{timestamp: int}")]
    [Route("api/ScoInfo/{activityId}/{studentid}/{timestamp}")]