We use cookies and similar technologies that are necessary to operate the website. Additional cookies are used to perform analysis of website usage. please read our Privacy Policy

How to Create Web API using ASP.NET Core & Entity Framework

img

In the world that is dominated with mobile apps and modern web applications, HTTP has kind of become a default option for developing feature-rich, robust, and scalable services.

HTTP or the Hypertext Transfer Protocol is basically a set of rules for transferring data on the World Wide Web. In technical terms, HTTP is an application protocol that executes on top of TCP/IP protocol.

Create Web API using ASP.NET Core & Entity Framework

The main benefit of HTTP protocol and the reason why it’s popular is because HTTP allows to reach a wide range of clients including mobile apps and browsers. And the Web API makes it easy to build such HTTP services.

webapi

Web API is simply a framework used for developing HTTP based services which can be accessible in different apps on multiple platforms such as windows, web, and mobile.

In the new ASP.NET Core framework, Microsoft and its community have combined the functionality of MVC and Web API.

In this tutorial, we will explain how to create Web API in ASP.NET Core using Entity framework.

Prerequisites to Create Web API in ASP.NET Core using Entity framework

Visual Studio 2017 version 15.7.3 or later with the following workloads:

  • NET and web development
  • .NET Core cross-platform development

.NET Core 2.1 SDK or later

Create the project

Follow these steps in Visual Studio:

  • From the Filemenu, select New > Project.
  • Select the ASP.NET Core Web Application template. Name the project CoreApiApp and click OKchoose the ASP.NET Core version. Select the API template and click OK.

CoreApiApp

image3

Launch the app

In Visual Studio, press CTRL+F5 to launch the app. Visual Studio launches a browser and navigates to http://localhost:<port>/api/values

Browser display the following output:

[“value1”, “value2”]

Install Entity Framework

To use EF Core, install the some packages for the database provider(s) you want to target.

To install page go to Tools > NuGet Package Manager > Package Manager Console

  1. Install-Package Microsoft.EntityFrameworkCore.SqlServer
  2. Install-Package Microsoft.EntityFrameworkCore.Tools
  3. Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

Generate EF Model through Reverse Engineering model

  • Tools –> NuGet Package Manager –> Package Manager Console
  • Run the following command to create a model from the existing database:

Scaffold-DbContext
“Server=mssqllocaldb;Database=SocietyManagement;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

This will create the Model class which looks like below for our application:

using System;
using System.Collections.Generic;

namespace SMSApi.Models
{	
    public partial class Members
    {
        public Guid MemberId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public int? Gender { get; set; }
        public int? Occupier { get; set; }
        public int? MntncPaidFreq { get; set; }
        public int? Maintenance { get; set; }
    }
}

Register and configure your context in Startup.cs

  • Open cs

Add the following using statements : –

using EFGetStarted.AspNetCore.ExistingDb.Models;

using Microsoft.EntityFrameworkCore;

Now we can use the AddDbContext(…) method to register it as a service.

  • Locate the ConfigureServices(…)method
  • Add the following code to register the context as a service
public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));
            services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            var connection = @"Server=192.168.1.95\sql2014;Initial Catalog=SocietyManagement;User Id=flex;Password=flex";
            services.AddDbContext<SocietyManagementContext>(options => options.UseSqlServer(connection));
        }

Here, we have set up CORS for the application add the Microsoft.AspNetCore.Cors package to your project. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others.

We have used CorsAuthorizationFilterFactory filter, to enable CORS globally for all controllers

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseCors("MyPolicy");
            app.UseHttpsRedirection();
            app.UseMvc();
        }

To enable CORS for your entire application add the CORS middleware to your request pipeline using the UseCors extension method.

 Add a controller

In Solution Explorer, right-click the Controllers folder. Select Add > New Item. In the Add New Itemdialog, select the API Controller Class template. Name the class MemberController, and click Add.

API Controller Class

Replace the class with the following code.

[Route("api/[controller]/[action]")]
    public class MemberController : Controller
    {
        private SocietyManagementContext _dbContext;
        public MemberController(SocietyManagementContext context)
        {
            _dbContext = context;
        }

    }

The controller’s constructor uses Dependency Injection to inject the database context into the controller. The database context is used in each of the CRUD methods in the controller. The constructor adds an item to the in-memory database if one doesn’t exist.

Implement the CRUD Operations :

In the following sections, CreateRead, Update and Delete methods are added to the controller.

Open the Controller class and add following code to ge member records.

// GET: api/<controller>
        [HttpGet]
        public IEnumerable<Members> Get()
        {
            return _dbContext.Members.ToList();
        }

        // GET api/<controller>/5
        [HttpGet("{id}")]
        public ActionResult<Members> GetById(int id)
        {
            var item = _dbContext.Members.Find(id);
            if (item == null)
            {
                return NotFound();
            }
            return item;
        }

These methods implement the two GET methods:

  • GET /api/member/
  • GET /api/member/{id}

Here’s a sample HTTP response for the Get method:

[
    {
        "memberId": "6c06dff2-4557-4f1b-9a6b-724c5fddb27d",
        "firstName": "Santosh",
        "lastName": "G",
        "middleName": "Kumar",
        "mobileNo": 947856324,
        "emailId": "kumar@gmail.com"
    }
]

Routing and URL paths

The [HttpGet] attribute denotes a method that responds to an HTTP GET request. The URL path for each method is constructed as follows:

  • Take the template string in the controller’s Routeattribute:
[Route("api/[controller]")]
    public class MemberController : Controller
    {
        private SocietyManagementContext _dbContext;
  • Replace [controller]with the name of the controller, which is the controller class name minus the “Controller” suffix. For this sample, the controller class name is MemberController and the root name is “member”. ASP.NET Core routing is case insensitive.
  • If the [HttpGet]attribute has a route template (such as [HttpGet(“/products”)], append that to the path. This sample doesn’t use a template. For more information, see Attribute routing with Http[Verb] attributes.

In the following GetById method, “{id}” is a placeholder variable for the unique identifier of the to-do item. When GetById is invoked, it assigns the value of “{id}” in the URL to the method’s id parameter.

 [HttpGet("{id}", Name = "GetById")]
        public ActionResult<Members> GetById(Guid id)
        {
            var item = _dbContext.Members.Find(id);
            if (item == null)
            {
                return NotFound();
            }
            return item;
        }

Create: Add the following Create method:

 [HttpPost]
        public IActionResult CreateMember([FromBody]Members model)
        {
            model.MemberId = Guid.NewGuid();
            _dbContext.Members.Add(model);
            _dbContext.SaveChanges();
            return CreatedAtRoute("GetById", new { id = model.MemberId }, model);
        }

The preceding code is an HTTP POST method, as indicated by the [HttpPost] attribute. MVC gets the value of the to-do item from the body of the HTTP request.

The CreatedAtRoute method:

  • Returns a 201 response. HTTP 201 is the standard response for an HTTP POST method that creates a new resource on the server.
  • Uses the “Get” named route to create the URL. The “Get” named route is defined in GetById

Update: Add the following Update method:

 [HttpPut("{id}")]
        [ActionName("UpdateMember")]
        public IActionResult UpdateMember(Guid id, [FromBody] Members model)
        {
            var member = _dbContext.Members.Find(id);
            if (member == null)
            {
                return NotFound();
            }
            member.FirstName = model.FirstName;
            member.MiddleName = model.MiddleName;
            member.LastName = model.LastName;
            member.MobileNo = model.MobileNo;
            member.EmailId = model.EmailId;
            _dbContext.Members.Update(member);
            _dbContext.SaveChanges();
            return NoContent();
        }

Update is similar to Create, except it uses HTTP PUT. The response is 204 (No Content). According to the HTTP specification, a PUT request requires the client to send the entire updated entity, not just the deltas. To support partial updates, use HTTP PATCH.

Delete: Add the following Delete method:

 	 [HttpDelete("{id}")]
        [ActionName("deleteMember")]
        public IActionResult deleteMember(Guid id)
        {
            var member = _dbContext.Members.Find(id);
            if (member == null)
            {
                return NotFound();
            }
            _dbContext.Members.Remove(member);
            _dbContext.SaveChanges();
            return NoContent();
        }

The Delete response is 204.

Conclusion:

In this tutorial, we first created a new ASP.NET Core web application, then created web API using Entity framework, and implemented CRUD operations. If you face any problem while implementing the above steps, you can contact to hire dedicated .NET developers for Microsoft technologies solutions for your projects.

Get a free copy of ASP.NET Core Web API Demo from Github.

 

We are here

Our team is always eager to know what you are looking for. Drop them a Hi!

    100% confidential and secure

    Pranjal Mehta

    Pranjal Mehta is the Managing Director of Zealous System, a leading software solutions provider. Having 10+ years of experience and clientele across the globe, he is always curious to stay ahead in the market by inculcating latest technologies and trends in Zealous.

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Table Of Contents