Click here to Skip to main content
13,193,048 members (65,494 online)
Click here to Skip to main content
Add your own
alternative version

Stats

8K views
158 downloads
8 bookmarked
Posted 16 Nov 2016

ASP.NET Core, WEB API and Repository Class

, 16 Nov 2016
Rate this:
Please Sign up or sign in to vote.
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 2016


My Interview on Microsoft TechNet Wiki Ninja Link




His Blog


Syed Shanu is basically from Madurai, Tamil Nadu, India.He was been working in South Korea for past 8 years. He started programming with Basic Language and C language from his high school at 1999.In 2005 he completed his Master of Computer Application. He started his working Career from Dec 2004 with ASP.

He has 10+ years of Experience in Microsoft Technologies.

His work experience with Language and Technology start’s from ASP and SQL Server, Then VB.NET and C# for PDA Application, Touch Screen Application Development, Desktop Application, ASP.NET Web Application Development, MVC and WPF.

He loves to work with Microsoft technology as he started to work on .Net Frame Work version from 1.0 to 4.5.

He had worked with HMI (Human Machine Interface) programs like PLC, Nutrunner Tools, and Sensor programs, RFID programs, Barcode programs and etc.

He usually uses his free time to spend with his Family and go outing. He loves photography and Hiking.

ASP.NET Article of the Day

1) Title : Draw ASP.NET Bar Chart Using HTML5 and jQuery Date : July 8, 2015
2) Title : ASP.NET Web Photo Editing Tool using HTML 5 Date : July 8, 2015
3) Title : MVC AngularJS and WCF Rest Service For Mind Reader Quiz Date : May 18, 2015
4) Title : AngularJS Shopping Cart Using MVC and WCF Rest Service Date : April 10, 2015
5) Title : Insert select update delete in asp.net with Simple Log
6) Title : Project Scheduling Using ASP.Net GridView Date : December 26, 2014
7) Title : ASP.NET Web Painting Tool using HTML 5 Date : September 16, 2014

You may also be interested in...

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171017.2 | Last Updated 16 Nov 2016
Article Copyright 2016 by syed shanu
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid