rboe rboe - 3 months ago 29
ASP.NET (C#) Question

How to access query parameters like $orderBy in controller actions?

I am just reading the Microsoft REST API Guidlines (https://github.com/Microsoft/api-guidelines/blob/master/Guidelines.md) and there are query parameters described beginning with a dollar sign, e.g.

$orderBy
.


9.6 Sorting collections



The results of a collection query MAY be sorted based on property
values. The property is determined by the value of the $orderBy query
parameter.


Now if I try to define a method parameter like
$orderBy
in an action method then it is not syntactically correct (
$orderBy
is not a valid identifier).

public class ExampleController : Controller
{
// this is syntacically not correct
public IActionResult Collection(...., string $orderBy = null)
{
...
}
}


How can I access a query parameter beginning with a dollar sign in an action method of ASP.NET Core ?

Answer

Use FromQuery and set name [FromQuery(Name = "$orderBy")]string orderBy:

public class ExampleController : Controller
{        
    public IActionResult Collection(...., [FromQuery(Name = "$orderBy")]string orderBy = null)
    {
         ...
    }
}