Share via


ASP.NET Core, WEB API and Repository Class

Introduction

This will be the series of article. In this series, we will see one by one in detail about

  1. Introduction to ASP.NET Core, WEB API and Repository Class
  2. ASP.NET Core, WEB API and Repository Class display using MVC View
  3. ASP.NET Core CRUD using WEB API and Repository Class
  4. ASP.NET Core CRUD with Database using WEB API and Repository Class

In this article, we will see in detail about how to create ASP.NET Core with Repository pattern in the WEB API.

This will be the series of article in the first series will see how to create a simple ASP.NET Core application and creating our first WEB API with Repository Class and view our JSON output in our browser., 

Return to Top
WEB API
Web API is a simple and easy way to build HTTP Services for Browsers and Mobiles. It has the following four methods as Get/Post/Put and Delete where.

  • Get is used to request for the data. (Select)
  • Post is used to create a data. (Insert)
  • Put is used to update the data.
  • Delete used is to delete the data.

 Reference Link
Return to Top

Repository Class

The repository pattern allows us to create a new layer for our business logic and Database operations. We can user repository to store our data.to know more about repository check this link 

Prerequisites

  • Visual Studio 2015: We can download it from here.
  • *.NET Core 1.0.1: *download link,link2.

Return to Top

Step 1: Create our ASP.NET Core 1.0.1 Web Application.

After installing both Visual Studio 2015 and ASP.NET Core 1.0.1. Click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and select ASP.NET Core Web Application. Enter the Project Name and click OK.

Next select WEB API. Click OK.
Return to Top

Return to Top

Step 2: Creating Modules

To create our module class first, we create one folder in side our solution project.

Right click our solution > Click Add > Click New Folder


Name the folder as Models.
Return to Top

Creating Model Class

Right Click the Model Folder, add new class and name it as “StudentMasters.cs”

In this class, we declare our property variables. 
Return to Top

namespace ASPNETCOREWEBAPI.Models   
{   
    public class  StudentMasters   
    {   
        public string  StdName { get; set; }   
        public string  Email { get; set; }   
        public string  Phone { get; set; }   
        public string  Address { get; set; }   
    }   
}

Step 3: Repository Class

Creating Repository Class

Here we create a Repository class to inject in to our Controllers. To create a Repository class,

Right click on Models Folder and click Add Class.

Name the class as IStudentRepository .

Here we can see that I have given the class name starting with I as this class we will be using as Interface and here we will declare only our methods to be used in our StudentRepository class.
Return to Top

public interface  IStudentRepository   
    {   
        IEnumerable<StudentMasters> GetAll();   
        void Add(StudentMasters info);   
    }

In this interface, we have added only Get and Add method. In our next article, we will see in details for CRUD operations.

Creating a class to implement the interface.

Now we create one more class named “StudentRepository” inside Models folder**.**

In this class we create method to get all the student information and to add student Information’s.
Return to Top

using System;   
using System.Collections.Concurrent;   
using System.Collections.Generic;   
using System.Linq;   
using System.Threading.Tasks;   
namespace ASPNETCOREWEBAPI.Models   
{   
    public class  StudentRepository: IStudentRepository   
    {   
        private static  ConcurrentDictionary<string, StudentMasters> stdMaster = new  ConcurrentDictionary<string, StudentMasters>();   
    
        public StudentRepository()   
        {   
    
            Add(new StudentMasters   
            {   
                StdName = "Shanu",    
                Phone = "+821039120700",   
                Email = "syedshanumcain@gmail.com",   
                Address = "Seoul,Korea"  
            });   
    
        }   
    
        public IEnumerable<StudentMasters> GetAll()   
        {   
            return stdMaster.Values;   
        }   
    
        public void  Add(StudentMasters studentInfo)   
        {   
            stdMaster[studentInfo.StdName] = studentInfo;   
        }   
    }   
}

Adding Repository Class in Configure Services:

To Inject our repository in Controllers we need to register the repository class with Dependency Injection Container.

To understand what is Dependency Injection(DI) check this link 

Open the Stratup.cs file from our solution project
Return to Top


First we add the using to import our Models folder 

using ASPNETCOREWEBAPI.Models;

 Next we register our own services like the code below. 
Return to Top

services.AddSingleton<IStudentRepository, StudentRepository>();

  like this

// This method gets called by the runtime. Use this method to add services to the container.   
        public void  ConfigureServices(IServiceCollection services)   
        {   
            // Add framework services.   
            services.AddMvc();   
            services.AddSingleton<IStudentRepository, StudentRepository>();   
        }

 Step 4:Creating Controllers

Right Click the Controllers Folder > Click Add > Click New Item.
Return to Top


Select ASP.NET from left side> Select Web API Controller Class.

Give the controller name as “StudentController.cs”

By default, our Controller class will be like this 
Return to Top

using System;   
using System.Collections.Generic;   
using System.Linq;   
using System.Threading.Tasks;   
using Microsoft.AspNetCore.Mvc;   
    
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 ;  
    
namespace ASPNETCOREWEBAPI.Controllers   
{   
    [Route("api/[controller]")]   
    public class  StudentController : Controller   
    {   
        // GET: api/values   
        [HttpGet]   
        public IEnumerable<string> Get()   
        {   
            return new  string[] { "value1", "value2" };    
        }   
    
        // GET api/values/5   
        [HttpGet("{id}")]   
        public string  Get(int  id)   
        {   
            return "value";   
        }   
    
        // POST api/values   
        [HttpPost]   
        public void  Post([FromBody]string value)   
        {   
        }   
    
        // PUT api/values/5   
        [HttpPut("{id}")]   
        public void  Put(int  id, [FromBody]string  value)   
        {   
        }   
    
        // DELETE api/values/5   
        [HttpDelete("{id}")]   
        public void  Delete(int  id)   
        {   
        }   
    }   
}

Remove all the default method inside our controller and change like to add our code. 
Return to Top

using System;   
using System.Collections.Generic;   
using System.Linq;   
using System.Threading.Tasks;   
using Microsoft.AspNetCore.Mvc;   
    
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 ;  
    
namespace ASPNETCOREWEBAPI.Controllers   
{   
    [Route("api/[controller]")]   
    public class  StudentController : Controller   
    {   
    
}

First we add the using in our controller class

using ASPNETCOREWEBAPI.Models;

Next we will create object for our Models. 

[Route("api/[controller]")]   
    public class  StudentController : Controller   
    {   
        private List<StudentMasters> _stdInfo;   
    
}

Adding Sample Information

Next we add few sample student information to be get from our WEB API method. 
Return to Top

[Route("api/[controller]")]   
    public class  StudentController : Controller   
    {   
        private List<StudentMasters> _stdInfo;   
    
        public StudentController()   
        {   
            InitializeData();   
        }   
    
//To bind initial Student Information   
        private void  InitializeData()   
        {   
            _stdInfo = new  List<StudentMasters>();   
    
            var studentInfo1 = new  StudentMasters   
            {   
                StdName = "Shanu",    
                Phone = "+821039120700",   
                Email = "syedshanumcain@gmail.com",   
                Address = "Seoul,Korea"  
            };   
    
            var studentInfo2 = new  StudentMasters   
            {   
                StdName = "Afraz",    
                Phone = "+821000000700",   
                Email = "afraz@gmail.com",   
                Address = "Madurai,India"  
            };   
    
            var studentInfo3 = new  StudentMasters   
            {   
                StdName = "Afreen",    
                Phone = "+821012340700",   
                Email = "afreen@gmail.com",   
                Address = "Chennai,India"  
            };   
    
            _stdInfo.Add(studentInfo1);   
            _stdInfo.Add(studentInfo2);   
            _stdInfo.Add(studentInfo3);   
        }   
}

WEB API Get Method

Using this get method we return all the student information as JSON result. 
Return to Top

[Route("api/[controller]")]   
    public class  StudentController : Controller   
    {   
        private List<StudentMasters> _stdInfo;   
    
        public StudentController()   
        {   
            InitializeData();   
        }   
    
    
        //This will return all Student Information   
        [HttpGet]   
        public IEnumerable<StudentMasters> GetAll()   
        {   
            return _stdInfo;   
        }   
}

 Here is the complete code for our controller class with both Adding sample data and using WEB API Get method. 
Return to Top

using System;   
using System.Collections.Generic;   
using System.Linq;   
using System.Threading.Tasks;   
using Microsoft.AspNetCore.Mvc;   
using ASPNETCOREWEBAPI.Models;   
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 ;  
    
namespace ASPNETCOREWEBAPI.Controllers   
{   
    [Route("api/[controller]")]   
    public class  StudentController : Controller   
    {   
        private List<StudentMasters> _stdInfo;   
    
        public StudentController()   
        {   
            InitializeData();   
        }   
    
    
        //This will return all Student Information   
        [HttpGet]   
        public IEnumerable<StudentMasters> GetAll()   
        {   
            return _stdInfo;   
        }   
    
    
        //To bind initial Student Information   
        private void  InitializeData()   
        {   
            _stdInfo = new  List<StudentMasters>();   
    
            var studentInfo1 = new  StudentMasters   
            {   
                StdName = "Shanu",    
                Phone = "+821039120700",   
                Email = "syedshanumcain@gmail.com",   
                Address = "Seoul,Korea"  
            };   
    
            var studentInfo2 = new  StudentMasters   
            {   
                StdName = "Afraz",    
                Phone = "+821000000700",   
                Email = "afraz@gmail.com",   
                Address = "Madurai,India"  
            };   
    
            var studentInfo3 = new  StudentMasters   
            {   
                StdName = "Afreen",    
                Phone = "+821012340700",   
                Email = "afreen@gmail.com",   
                Address = "Chennai,India"  
            };   
    
            _stdInfo.Add(studentInfo1);   
            _stdInfo.Add(studentInfo2);   
            _stdInfo.Add(studentInfo3);   
        }   
    }   
}

Step 5: Run the application

To see the result runt the application .

When we run the application by default we can see the values controller result as values

http://localhost:64764/api/values
Return to Top

Change the Values with our newly created controller name as student “http://localhost:64764/api/student“. 

Here now we can see all our added student information has been displayed as JSON result.
Return to Top

Conclusion:

This will be series of article in this first series we have seen in details about our first ASP.NET Core, WEB API and Repository Class for Get method. In next series, we will see how to bind this result in our MVC View.
Return to Top

Download Code

You can download the Source Code from this link Download Source Code Return to Top

See Also