ASP.NET Core, WEB API and Repository Class






2.73/5 (8 votes)
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.
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.
Next select WEB API. Click OK.
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
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.
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:
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 the 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 methods 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 got 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, run the application.
When we run the application, by default, we can see the values controller result as values http://localhost:64764/api/values:
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.
History
- 17th November, 2016: Initial version