Saturday, August 10, 2019

Asp.Net Core API Controller with a GET Method

In the previous post we added Entity Framework Core context to the Web API project, in this post we will use the EF context to get a list of values from the DB and expose the data in JSON format using a HttpGet method.

To start with we will have to add a reference of the DataAccess project which we created in the previous post to the WebAPI project. All database operations will be performed in the DataAccess project hence we will add a reference to this project.

Next in the WebAPI project we will add a new API Controller, name it CountryController




Once the controller gets created, let us add a Get method which will use the Entity Framework Core context object to query and return a list of countries from the DB. Make sure to include the reference to Microsoft.EntityFrameworkCore in the controller class else the ToListAsync() methods will not be available in the context objects.

The Country controller with the Get method looks like this.

using DataAccess.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace HelloWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CountryController : ControllerBase
    {
        [HttpGet]
        public async Task<ActionResult<List<Country>>> Get()
        {
            var _context = new UserRegistrationContext();
            return await _context.Country.ToListAsync();
        }
    }
}


Build and run the project, in the browser enter the URL for the Get action method of the country controller.

http://localhost:51571/api/Country

The output will be as follows.




We can also use an API tool like Postman to access the API results.




Search Flipkart Products:
Flipkart.com

No comments: