Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Web Api in Asp.net core

Web Api in Asp.net core

Date- Dec 03,2022 Updated Feb 2026 5442 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 .Web Api in Aspnet core

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

Web Api in Aspnet core 2

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 

Web Api in Aspnet core 3Here, 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

Web Api in Aspnet core 4So , 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

Integrating Entity Framework Core with DB2 in ASP.NET Core Applications
Apr 08, 2026
Optimizing DB2 Queries in ASP.NET Core Applications
Apr 07, 2026
How to export view as pdf in Asp.Net Core
Jul 05, 2022
What is asp.net in web development
Apr 25, 2022
Previous in ASP.NET Core
Hangfire in ASP.NET Core 3.1 – Background Jobs
Next in ASP.NET Core
Reading json data from file using Asp.Net
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,938 views
  • 2
    Error-An error occurred while processing your request in .… 11,273 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 235 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,459 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 162 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,497 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,232 views

On this page

🎯

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 Password in Asp.Net 26066 views
  • Exception Handling Asp.Net Core 20797 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20288 views
  • How to implement Paypal in Asp.Net Core 19679 views
  • Task Scheduler in Asp.Net core 17578 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 | 1770
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
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • 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