Click here to Skip to main content
14,268,557 members

ASP.NET Core, WEB API and Repository Class

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

Introduction

In this article, we will see in detail about 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 user repository to store our data.to know more about repository check this link

Prerequisites

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

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.

Next select WEB API. Click OK.

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.

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.

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.

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’s.

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

First we add the using to import our Models folder

using ASPNETCOREWEBAPI.Models;

Next we register our own services like the code below.

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

Here is complete Startup.cs class

Step 4: Creating Controllers

Right Click the Controllers Folder > Click Add > Click New Item.

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

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.

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.

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

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

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

Chaange 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.

History

ASPNETCOREWEBAPI.zip - 2016-11-17

License

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

Share

About the Author

syed shanu
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.

Article
Posted 16 Nov 2016

Stats

15.2K views
273 downloads
8 bookmarked