Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular
    • C
    • c#
    • C#
    • HTML/CSS
    • Java
    • JavaScript
    • Node.js
    • Python
    • React
    • Security
    • SQL Server
    • TypeScript
  • Post Blog
  • Tools
    • JSON Beautifier
    • HTML Beautifier
    • XML Beautifier
    • CSS Beautifier
    • JS Beautifier
    • PDF Editor
    • Word Counter
    • Base64 Encode/Decode
    • Diff Checker
    • JSON to CSV
    • Password Generator
    • SEO Analyzer
    • Background Remover
  1. Home
  2. Blog
  3. How to Build a Web API in ASP.NET Core: Step-by-Step

How to Build a Web API in ASP.NET Core: Step-by-Step

Date- Dec 03,2022

5395

Free Download Pay & Download
Web Api Api

Web Api in Asp.Net Core

First of all , for creating web api's in asp.net core you have to take one new project based on Asp.Net core MVC 3.1. Now after taking the new project we will add one new api controller and add following code there

namespace RedisCache.Models
{
    public class Product
    {
        public int ProductID { get; set; }

        public string ProductCategory{ get; set; }
       
        public string SubCategory { get; set; }
        
        public string ProductName { get; set; }
      
        public string ProductDescription { get; set; }

        public decimal ProductPrice { get; set; }
 
        public decimal ProductWeight { get; set; }
 
        public int Units { get; set; }
 
        public decimal Total { get; set; }
 
    }
}

First of all we have to add this model in our project as we are using Entity framework core.

Now after adding the model we can create api's in our project using entity framework. You can copy following code

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using RedisCache.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace RedisCache.Controllers
{
 
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly DbEmployeeContext _context;
       

        public ProductController(DbEmployeeContext context)
        {
            _context = context;
           
        }

        [HttpGet]
        [Route("api/Product/GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var products = await _context.Products.ToListAsync();

            return Ok(products);
        }

        [HttpPost]
        [Route("api/Product/Create")]
        public async Task<IActionResult> Create(Product product)
        {
            var result= _context.Products.Add(product);
            _context.SaveChanges();
            return Ok(product);
        }

        [HttpPut]
        [Route("api/Product/Update")]
        public async Task<IActionResult> Update(Product product)
        {
           
                var existingProduct =await _context.Products.FirstOrDefaultAsync(x=>x.ProductID==product.ProductID);

                if (existingProduct != null)
                {
                    existingProduct.ProductName = product.ProductName;
                    existingProduct.ProductDescription = product.ProductDescription;
                    existingProduct.ProductCategory = product.ProductCategory;
                    existingProduct.SubCategory = product.SubCategory;
                    _context.SaveChanges();
                }
                else
                {
                    return NotFound();
                }
            

            return Ok("Success");
        }
        [HttpDelete]
        [Route("api/Product/Delete")]
        public async Task<IActionResult> Delete(int id)
        {

            var existingStudent = await _context.Products.FirstOrDefaultAsync(x => x.ProductID == id);

            _context.Entry(existingStudent).State = EntityState.Deleted;
           _context.SaveChanges();

            return Ok("Record Deleted");
        }

    }
}

Here we are using entity framework for performing crud operation. So here you will see different type of api's created. We will discuss them one by one

HttpGet - So the first api we will create is GetAll . This api is basically for getting the list of data  from the database. Here we have used a database which has Product table in it.

[HttpGet]
[Route("api/Product/GetAll")]
public async Task<IActionResult> GetAll()
{
     var products = await _context.Products.ToListAsync();
    return Ok(products);
}

So , for testing this api we will use postman. You can download postman and there we have to call the url like this .

So, here you can see the list of Products returned back in the response. Make sure to use Get for a api of type HttpGet.  

HttpPost - Now we will create HttpPost api for create operation. You can copy the code from below

[HttpPost]
[Route("api/Product/Create")]
public async Task<IActionResult> Create(Product product)
{
     var result= _context.Products.Add(product);
     _context.SaveChanges();
     return Ok(product);
}

So, we will call the Create api by passing the object as json in postman. You can have a look at the image below

This will add one new record in the database.You have to use HttpPost for create operations.

HttpPut- Now we will have a look at HttpPut api which is for update operations. You can create an update api like this.

[HttpPut]
[Route("api/Product/Update")]
public async Task<IActionResult> Update(Product product)
{
   
        var existingProduct =await _context.Products.FirstOrDefaultAsync(x=>x.ProductID==product.ProductID);

        if (existingProduct != null)
        {
            existingProduct.ProductName = product.ProductName;
            existingProduct.ProductDescription = product.ProductDescription;
            existingProduct.ProductCategory = product.ProductCategory;
            existingProduct.SubCategory = product.SubCategory;
            _context.SaveChanges();
        }
        else
        {
            return NotFound();
        }
    

    return Ok("Success");
}

So, for calling the api we will use this 

Here, you have to make sure you choose Put here in the postman as we are using HttpPut api.

HttpDelete -  For delete operation we often use HttpDelete api. You can copy the delete api from here

[HttpDelete]
[Route("api/Product/Delete")]
public async Task<IActionResult> Delete(int id)
{

    var existingStudent = await _context.Products.FirstOrDefaultAsync(x => x.ProductID == id);

    _context.Entry(existingStudent).State = EntityState.Deleted;
   _context.SaveChanges();

    return Ok("Record Deleted");
}

For calling the api we have to do this in postman

So , this is how we can delete the record using HttpDelete Api. 

This is how we can create Web Api in Asp.net core.

S
Shubham Batra
Programming author at Code2Night โ€” sharing tutorials on ASP.NET, C#, and more.
View all posts โ†’

Related Articles

How to Export View as PDF in ASP.NET Core: Complete Guide
Jul 05, 2022
Step-by-Step: Upload Files to Azure Blob Storage in ASP.NET Core
Feb 27, 2023
Ultimate Guide to Using Azure Blob Storage in ASP.NET Core
Feb 26, 2023
How to Implement PayPal in ASP.NET Core: Ultimate Guide
Oct 30, 2022
Previous in ASP.NET Core
How to Use Hangfire in ASP.NET Core 3.1 for Background Jobs
Next in ASP.NET Core
How to Read JSON Data from a File in ASP.NET Core

Comments

Contents

๐ŸŽฏ

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Passwords in ASP.NET: A Guide 25946 views
  • Exception Handling in ASP.NET Core: Best Practices 20722 views
  • HTTP Error 500.31: Failed to Load ASP.NET Core Runtime 20202 views
  • Task Scheduling Made Easy in ASP.NET Core: Step-by-Step 17502 views
  • Implement Stripe Payment Gateway in ASP.NET Core: Step-by-St… 16748 views
View all ASP.NET Core posts โ†’

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Free Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Diff Checker
  • Base64 Encode/Decode
  • Word Counter
  • SEO Analyzer
By Language
  • Angular
  • C
  • c#
  • C#
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ยท  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor