Roddy Balkan
Roddy Balkan

Reputation: 1639

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

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}")]

Upvotes: 3

Views: 13712

Answers (2)

Nkosi
Nkosi

Reputation: 247133

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

Upvotes: 5

Paul Mendoza
Paul Mendoza

Reputation: 11

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)

Upvotes: 1

Related Questions