Click here to Skip to main content
15,444,490 members
Articles / Web Development / ASP.NET
Article
Posted 16 Nov 2016

Stats

22.2K views
326 downloads
8 bookmarked

ASP.NET Core, WEB API and Repository Class

Rate me:
Please Sign up or sign in to vote.
2.73/5 (8 votes)
16 Nov 2016CPOL3 min read
In this article, we will see in detail how to create ASP.NET Core with Repository pattern in the WEB API.

Introduction

This article shows how to create ASP.NET Core with Repository pattern in the WEB API.

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

Repository Class

Repository Patten allows us to create a new layer for our business logics and database operations. We can use repository to store our data. To know more about repository, check this link.

Prerequisites

Using the Code

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 your Project Name and click OK.

Image 1

Next select WEB API. Click OK.

Image 2

Step 2: Creating Modules

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

Right click our solution > click Add > click New Folder

Image 3

Name the folder as Models.

Image 4

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.

C#
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.

C#
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 inside Models folder as “StudentRepository”.

In this class, we create method to get all the student information and to add student Information.

C#
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 Startup.cs file from our solution project:

Image 5

First, we add the using to import our Models folder:

C#
using ASPNETCOREWEBAPI.Models;

Next, we register our own services like the code below:

C#
services.AddSingleton<IStudentRepository, StudentRepository>();

like this:

C#
// 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>();
        }

Here is the complete Startup.cs class:

Image 6

Step 4: Creating Controllers

Right click the Controllers folder > click Add > click New Item.

Image 7

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

Give your controller name as “StudentController.cs”.

By default, our Controller class will be like this:

C#
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 methods inside our controller and change like to add our code.

C#
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:

C#
using ASPNETCOREWEBAPI.Models;

Next, we will create object for our Models.

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

Adding Sample Information

Next, we add few sample student information to be got from our WEB API method.

C#
[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.

C#
[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.

C#
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, run the application.

When we run the application, by default, we can see the values controller result as values http://localhost:64764/api/values:

Image 8

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.

Image 9

History

  • 17th November, 2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionRepository connected to Database Pin
Member 1271965811-Sep-17 16:23
MemberMember 1271965811-Sep-17 16:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.