0

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

3
  • 3
    You should do some tutorials that teach the basics. Commented Jul 6, 2018 at 13:49
  • 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! Commented Jul 6, 2018 at 13:56
  • Always start with the documentation before asking a question here: learn.microsoft.com/en-us/aspnet/core/mvc/controllers/… Commented Jul 6, 2018 at 13:57

1 Answer 1

3

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?}");
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.