Simple a Web API using ASP.NET Core

In this article, I am going to show you how to build an ASP.NET Core Web API in the back end


First of all, create an ASP.NET Core Web API


In Visual Studio 2019 Community, click the "Create a new project" option.


Select the "ASP.NET Core Web Application" option.


I provide the project name and the solution name as called "Order".


Once you provide the project name and the solution name, a new window will be opened as follows.


simplewebapi_aspnetcore_1.png

Select the drop down lists as you can see above. Then select the "API" option and unchecked Configure for HTTPS.


Click the "Create" button.


Setup Database


In this project, I’ll be using Entity Framework Core for doing database operations.


I have to install corresponding NuGet packages. On the Solution Explorer, right click the project. Select the "Manage NuGet packages…" option.


Select the "Browse" tab.


Serach the "Microsoft.EntityFrameworkCore" word as follows. Then install three packages as shown below.


simplewebapi_aspnetcore_2.png

simplewebapi_aspnetcore_3.png

Create a database model class


Create a folder named Models into the root directory. Then right click the Models folder. Go to Add >New Items. Select the "Class" option. Name as Order.cs, then click the "Add" button.


using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Order.Models
{
    public class Order
    {
        [Key]
        public int ID { get; set; }
		[Required]
        [Column(TypeName = "nvarchar(100)")]
        public string Name { get; set; }
		[Required]
        public int Quantity { get; set; }
		[Required]
        [Column(TypeName = "varchar(10)")]
        public string ReceivedDate { get; set; }
    }
}

Let’s create DbContext class into the Models folder.


Right click the Models folder. Go to Add > New Item. Select the "Class" option. Name as OrderContext.cs, then click the "Add" button.


using Microsoft.EntityFrameworkCore;
namespace Order.Models
{
    public class OrderContext : DbContext
    {
        public OrderContext(DbContextOptions options):base(options)
        { }
		public DbSet Orders { get; set; }
    }
}

OrderContext class specifies what will be added to the physical database during migration. I have added the DbSet property for the Order model class. So that it will be created a new table "Order" in the physical database, after migration.


The parameter "options" is used to specify the database provider(SQL Server) and the connnection string . To specify that, we will be using DI (Dependency Injection) in the "Startup.cs" class as shown below.


public void ConfigureServices(IServiceCollection services)
{
	...
	services.AddDbContext(options => 
		options.UseSqlServer(Configuration.GetConnectionString("OrderConnection")));
}

Open the appsettings.json file. Paste the following code snippet.


{
  ...
  "ConnectionStrings": {
    "OrderConnection": "Server=localhost\\SQLEXPRESS;Database=OrderDB;Trusted_Connection=True;MultipleActiveResultSets=True;"
  }
}

So that the OrderConnection key used in the Startup.cs file is defined in the appsettings.json file.


For database I’ve done everything. Let’s do the migration.


Go to Tools > NuGet Package Manager from the menu. Open the Package Manager Console.


simplewebapi_aspnetcore_4.png

Add-Migration "InitialCreate"
Update-Database

simplewebapi_aspnetcore_5.png

After successful migration, the OrderDB database and Orders table in Microsoft SQL Server Management Studio will look like the following.


simplewebapi_aspnetcore_6.png

simplewebapi_aspnetcore_7.png

Also a new folder "Migrations" will be created as follows.


simplewebapi_aspnetcore_8.png

Create an API Controller


Right click on the Controllers folder. Go to Add > Controller...


Select the "API Controller with actions, using Entity Framework" option from the coming dialog. So that we can create an API Controller with CRUD operations.


After clicking the "Add" button, a dialog box will be appeared like the following.


simplewebapi_aspnetcore_9.png

New controller will be created automatically by scaffolding mechanism.


using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Order.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Order.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        private readonly OrderContext _context;
		public OrderController(OrderContext context)
        {
            _context = context;
        }
		// GET: api/Order
        [HttpGet]
        public async Task>> GetOrders()
        {
            return await _context.Orders.ToListAsync();
        }
		// GET: api/Order/5
        [HttpGet("{id}")]
        public async Task> GetOrder(int id)
        {
            var order = await _context.Orders.FindAsync(id);
			if (order == null)
            {
                return NotFound();
            }
			return order;
        }
		// PUT: api/Order/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPut("{id}")]
        public async Task PutOrder(int id, Order.Models.Order order)
        {
            if (id != order.ID)
            {
                return BadRequest();
            }
			_context.Entry(order).State = EntityState.Modified;
			try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!OrderExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
			return NoContent();
        }
		// POST: api/Order
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPost]
        public async Task> PostOrder(Order.Models.Order order)
        {
            _context.Orders.Add(order);
            await _context.SaveChangesAsync();
			return CreatedAtAction("GetOrder", new { id = order.ID }, order);
        }
		// DELETE: api/Order/5
        [HttpDelete("{id}")]
        public async Task> DeleteOrder(int id)
        {
            var order = await _context.Orders.FindAsync(id);
            if (order == null)
            {
                return NotFound();
            }
			_context.Orders.Remove(order);
            await _context.SaveChangesAsync();
			return order;
        }
		private bool OrderExists(int id)
        {
            return _context.Orders.Any(e => e.ID == id);
        }
    }
}

It contains CRUD(Create, Read, Update and Delete) operations. The context parameter of the constructor of the OrderController is set by DI(Dependency Injection) in the Startup.cs


simplewebapi_aspnetcore_10.png

You can test the API using Postman app.


Start the project. (Press the "F5" key)


http://localhost:[yourportnumber]/api/Order


Since there is no data, the web page will be empty.


simplewebapi_aspnetcore_11.png

Open Postman app to post an order to the OrderController class


Request Body


{
 "name":"1L Milk",
 "quantity":1,
 "receiveddate":"04/19/2020"
}

simplewebapi_aspnetcore_12.png

After sending the above request, you will see a response as shown below.


simplewebapi_aspnetcore_13.png

We can do the previous GET method again as follows.


simplewebapi_aspnetcore_14.png

I now have a record in the database


simplewebapi_aspnetcore_15.png

I hope you have understood. Thanks for reading.


Happy Coding :)


https://github.com/cihanasn/Order