Saturday, August 17, 2019

Attribute Routing in Asp.Net Core Web API

In the previous posts we saw on how to use the HTTP verbs GET, POST, PUT & DELETE to invoke different action methods in an Asp.Net Core WebAPI controller, this approach holds good as long as we have only one Action method per verb in a controller, what if we want multiple methods with the same header or if we want to have custom routing to each action method, this is where attribute routing can help us. In this post we shall see on how to define custom routes to action methods using attribute routing.

Let us another controller DepartmentController, and add a Get method with a custom routing attribute as follows.

    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController : ControllerBase
    {
        [HttpGet("GetDepartments")]
        public async Task>> Get()
        {
            var _context = new UserRegistrationContext();
            return await _context.Department.ToListAsync();
        }
    }

Build and run the project, this time we will use the custom Route api/Department/GetDepartments




Search Flipkart Products:
Flipkart.com

No comments: