CRUD demonstration using WebAPI with ASP.NET Core MVC using inbuilt DI container and Google PostMan

Rajnilari2015
Posted by in ASP.NET Core category on for Beginner level | Points: 250 | Views : 957 red flag
Rating: 4 out of 5  
 1 vote(s)

In this article we will look into the interaction between both these technologies with a step by step guidance by using WebAPI with ASP.NET Core MVC using inbuilt DI container and testing the same through Google PostMan


 Download source code for CRUD demonstration using WebAPI with ASP.NET Core MVC using inbuilt DI container and Google PostMan

Recommendation
Read Let's Explore ASP.NET Core 1.0 briefly before this article.

Introduction

ASP.NET Core has built-in support for building Web APIs and MVC controllers. Since these two frameworks now share the same code base and pipeline, so clubbing these two frameworks makes it simpler to build apps which includes both UI and APIs.

Postman is a Google Chrome app for interacting with HTTP APIs that presents a GUI for constructing requests and reading responses.

In this article we will look into the interaction between both these technologies with a step by step guidance by using WebAPI with ASP.NET Core MVC using inbuilt DI container and testing the same through Google PostMan.

Creating the WebAPI project

Fire up Visual Studio 2015 and then File -> New -> Project -> Web -> Asp.net Core Web Applications(.Net Core).Choose the target Framework as .Net Framework 4.6.1.

The next screen that pops up display's a list of templates and we need to choose Web API template.

ASP.NET Core 1.0 includes only Web API and MVC but not SignalR or Web Pages yet. We choose the Web API and Click "OK" button and here is our "Welcome Screen"

Create a Model Class

Now let us first create a folder by the name "Model". Then add Employee model as under

namespace WebAPI_Asp.netCore.Model
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
        public string EmailAddress { get; set; }
        public string PhoneNumber { get; set; }
    }
}

Our Employee model is a simple Employee Class which has some scalar properties like EmployeeID,EmployeeName,EmailAddress,PhoneNumber This Employee model represents the data model in our application.

Create the Repository objects

The repository objects are responsible for encapsulating the data layer. It contains logic for retrieving data and mapping it to an entity model.

Now let us first create a folder by the name "Repository" and first create an interface say IEmployeeRepository.cs inside that folder. This interface is responsible for the CRUD operation

using System.Collections.Generic;
using WebAPI_Asp.netCore.Model;

namespace WebAPI_Asp.netCore.Repository
{
    public interface IEmployeeRepository
    {
        List<Employee> InsertEmployee(Employee employee);
        List<Employee> GetEmployees();
        List<Employee> UpdateEmployee(Employee employee);
        List<Employee> DeleteEmployee(int employeeID);
    }
}

Next we need to have a concrete repository class which will implement the IEmployeeRepository interface. Let us add EmployeeRepository.cs class that will implement the IEmployeeRepository and will provide the concrete implementation for the same.

using System.Collections.Generic;
using WebAPI_Asp.netCore.Model;
using System.Linq;

namespace WebAPI_Asp.netCore.Repository
{
    public class EmployeeRepository : IEmployeeRepository
    {
        private List<Employee> employees = new List<Employee>();

        public EmployeeRepository()
        {
            employees = GetEmployees();
        }

        /// <summary>
        /// Function: GetEmployees
        /// Get the Employee Records
        /// </summary>
        /// <returns></returns>
        public List<Employee> GetEmployees()
        {
            return new List<Employee>()
            {
                new Employee { EmployeeID = 1, EmployeeName = "Niladri Biswas", EmailAddress = "niladri@test.com", PhoneNumber = "123456789"}
                ,new Employee { EmployeeID = 2, EmployeeName = "Arina Biswas", EmailAddress = "arina@test.com", PhoneNumber = "234567891" }
                ,new Employee { EmployeeID = 3, EmployeeName = "Rajlaxmi Biswas", EmailAddress = "rajlaxmi@test.com", PhoneNumber = "456789123" }
                ,new Employee { EmployeeID = 4, EmployeeName = "RNA Team", EmailAddress = "rna@test.com", PhoneNumber = "56712343267" }
            };
        }

        /// <summary>
        /// Function: InsertEmployee
        /// Insert an Employee record
        /// </summary>
        /// <param name="employee"></param>
        /// <returns></returns>
        public List<Employee> InsertEmployee(Employee employee)
        {            
            employees.Add(employee);
            return employees;
        }

        /// <summary>
        /// Function: UpdateEmployee
        /// Update an Employee record
        /// </summary>
        /// <param name="employee"></param>
        /// <returns></returns>
        public List<Employee> UpdateEmployee(Employee employee)
        {            
            var empRecord = employees.Find(e => e.EmployeeID == employee.EmployeeID);
            if (empRecord != null)
            {
                employees.Remove(empRecord);
                employees.Add(employee);
            }
            return employees.OrderBy(o => o.EmployeeID).ToList();
        }

        public List<Employee> DeleteEmployee(int employeeID)
        {             
            var empRecord = employees.Find(e => e.EmployeeID == employeeID);
            if (empRecord != null)
            {
                employees.Remove(empRecord);                   
            }
            return employees;
        }
    }
}

The EmployeeRepository is a concrete implementation. In the GetEmployees() method, we fetch the Employee Records. The InsertEmployee(Employee employee) takes an instance of Employee, adds that to the existing List<Employee> colleciton by using the Add method and returns the new collection. The UpdateEmployee(Employee employee) method, first checks if an employee record exists from the supplied EmployeeID and once a match is found, it first deletes the record from the existing collection and then adds the new record. And finally, the DeleteEmployee(int employeeID) method, first checks if an employee record exists from the supplied employeeID and once a match is found, it first deletes the record and then returns the new collection.

Register the repository to the ASP.NET Core's dependency injection

Instead of instantiating the EmployeeRepository inside the controller, we will register the repository to the built-in ASP.NET Core's dependency injection. For that, let's open the Startup.cs file and in the ConfigureServices method, add the below code

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.           
    services.AddSingleton<IEmployeeRepository, EmployeeRepository>();
}

The AddSingleton method, adds a singleton service of the type specified in TService with an implementation type specified in TImplementation to the specified Microsoft.Extensions.DependencyInjection.IServiceCollection. It returns a reference to this instance after the operation has completed.

The general syntax is

public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services)
            where TService : class
            where TImplementation : class, TService;

Services can be registered with the container in several ways.In this case we are using Singleton Service by using the AddSingleton<IService, Service>() method.Singleton lifetime services are created the first time they are requested and then every subsequent request will use the same instance. If the application requires singleton behavior, allowing the services container to manage the service's lifetime is recommended instead of implementing the singleton design pattern and managing the object's lifetime in the class.

The complete Startup.cs file looks as under

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using WebAPI_Asp.netCore.Repository;

namespace WebAPI_Asp.netCore
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // 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<IEmployeeRepository, EmployeeRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();
        }
    }
}

Now expand the Controllers folder and create EmployeeController.cs and add the following code

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using WebAPI_Asp.netCore.Model;
using WebAPI_Asp.netCore.Repository;

namespace WebAPI_Asp.netCore.Controllers
{    
    [Route("Employee")]
    public class EmployeeController : Controller
    {
        public EmployeeController(IEmployeeRepository employees)
        {
            EmployeeRecords = employees;
        }
        public IEmployeeRepository EmployeeRecords { get; set; }
        
        [HttpGet]
        [Route("EmployeeRecords")]
        public IEnumerable<Employee> GetAllEmployees()
        {
            return EmployeeRecords.GetEmployees();
        }

        [Route("InsertEmployeeRecord")]
        [HttpPost]
        public List<Employee> InsertEmployeeRecords([FromBody]Employee emp)
        {
            return EmployeeRecords.InsertEmployee(emp);
        }

        [Route("UpdateEmployeeRecord")]
        [HttpPut]
        public List<Employee> UpdateEmployeeRecords([FromBody] Employee emp)
        {
            return EmployeeRecords.UpdateEmployee(emp);
        }

        [Route("DeleteEmployeeRecord")]
        [HttpDelete]
        public List<Employee> DeleteEmployeeRecords(int employeeId)
        {
            return EmployeeRecords.DeleteEmployee(employeeId);
        }
    }
}

Now we can test the API Services of the EmployeeController.cs through PostMan.

Testing application through PostMan

  1. GET Request

    Open PostMan and write the URL(http://localhost:7625/Employee/EmployeeRecords), and choose Http method to GET and click on Send button. The result is as under

  2. POST Request

    Open PostMan and write the URL(http://localhost:7625/Employee/InsertEmployeeRecord), and choose Http method to POST, Tab on the Body, add the input JSON by tapping the raw radio button and click on Send button. The result is as under

  3. PUT Request

    Open PostMan and write the URL(http://localhost:7625/Employee/UpdateEmployeeRecord), and choose Http method to PUT, Tab on the Body, add the input JSON by tapping the raw radio button and click on Send button. The result is as under

  4. DELETE Request

    Open PostMan and write the URL(http://localhost:7625/Employee/DeleteEmployeeRecord?employeeId=1), and choose Http method to DELETE and click on Send button. The result is as under

N.B.~It is noteworthy to mention here that there is some interesting feature in the Headers

Let us discuss about the same in short

  1. Content-Type: It is the Mime-Type for this content which is application/json
  2. Date: The date and time the message was sent.
  3. Server: Kestrel server is used.
  4. Transfer-Encoding: The encoding used to transfer the entity to the user. It is set to Chunked indicating that Chunked transfer encoding data transfer mechanism of the Hypertext Transfer Protocol (HTTP) is initiated in which data is sent in a series of "chunks".
  5. X-Powered-By: It specifies the technology like Asp.net, Php etc. supporting teh web application.
  6. X-SourceFiles: It is the custom header. It contains the base64-encoded path to the source file on disk and is used to link a page's generated output back to that source file. It's only generated for localhost requests.

Reference

Conclusion

In this article, we have learnt about the use of WebAPI with ASP.NET Core MVC by using a CRUD operation and testing the same using Google Postman as the client. In addition to that, we have also seen how to use the inbuilt DI Container. Hope this will be helpful. Thanks for reading. Zipped file attached.

Recommendation
Read Let's Explore Diagnostics in ASP.NET Core 1.0 after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)