0
votes

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

1
You should do some tutorials that teach the basics.user47589
api/controller/EmployeesByAge/23 is not a good pattern to follow. It would probably be better to use a route like api/Employees?age=23. This way you can filter on multiple route queries in the future. For example you my one day want to add department or something, like api/Employees?age=23&dept=IT. Hope this makes sense. Good luck!BinaryNexus
Always start with the documentation before asking a question here: docs.microsoft.com/en-us/aspnet/core/mvc/controllers/…Chris Pratt

1 Answers

3
votes

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