Search code examples
c#asp.net-core-webapiasp.net-web-api-routing

Custom Actions in ASP.NET Core Web API


I am using ASP.NET core 2.0 Web API Template and I have a couple of doubts:

1)How can i create custom actions and map the URIs to them. Like I have an Employee Model and I want to create an API action (EmployeesByAge) which fetches employees having age more than the number which I supply to API. But I am not able to map to it.Like I want to hit the api like: api/controller/EmployeesByAge/23 but it is being mapped to the deault Get method and taking 'EmployeesByAge' as ID.So How can I define custom route.

2)Where are the routes defined? like in MVC they were in Startup.cs. Here I can't find the default routes except at the top of the controllers.

Thanks


Solution

  • You can redefine the Route per Attribute on the method:

    [HttpGet("filter/{age}")
    public IActionResult EmployeesByAge(int age) { }
    

    The (default) Route(s) are defined in Startup.cs (Microsoft Documentation).

    In the Configure-Method:

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });