Asp.Net Web Api Get Post Put Delete Methods Explained Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of ASP.NET Web API GET, POST, PUT, DELETE Methods Explained

ASP.NET Web API: GET, POST, PUT, DELETE Methods Explained

1. GET Method

The HTTP GET method is used to retrieve data from the server. This is a read-only method, and it should not have any side effects on the server. When a client sends a GET request, the server responds with the requested data usually in format like JSON or XML.

Use Case: Fetching a list of products, a specific user's details, etc.

Example:

// Controller Action
public IHttpActionResult GetProduct(int id)
{
    var product = _productRepository.GetProductById(id);
    if (product == null)
    {
        return NotFound();
    }
    return Ok(product);
}

Request: GET http://myapi.com/api/products/1 Response:

{
    "Id": 1,
    "Name": "Laptop",
    "Price": 1200.00
}

2. POST Method

The HTTP POST method is used to create a new resource on the server. When a client sends a POST request, it typically includes data in the body of the request. The server processes this data to create a new resource and returns the created resource or a success message.

Use Case: Submitting form data, creating a new user, etc.

Example:

// Controller Action
[HttpPost]
public IHttpActionResult CreateProduct(Product product)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var newProduct = _productRepository.AddProduct(product);
    return CreatedAtRoute("DefaultApi", new { id = newProduct.Id }, newProduct);
}

Request: POST http://myapi.com/api/products Body:

{
    "Name": "Smartphone",
    "Price": 700.00
}

Response:

{
    "Id": 2,
    "Name": "Smartphone",
    "Price": 700.00
}

3. PUT Method

The HTTP PUT method is used to update an existing resource on the server. The client sends the updated data in the body of the request, and the server updates the resource accordingly. PUT is an idempotent method, meaning making the same request multiple times has the same effect as making it once.

Use Case: Updating product details, changing user information, etc.

Example:

// Controller Action
[HttpPut]
public IHttpActionResult UpdateProduct(int id, Product product)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    if (id != product.Id)
    {
        return BadRequest("Product ID mismatch.");
    }

    var updatedProduct = _productRepository.UpdateProduct(product);
    if (updatedProduct == null)
    {
        return NotFound();
    }

    return Ok(updatedProduct);
}

Request: PUT http://myapi.com/api/products/2 Body:

{
    "Id": 2,
    "Name": "Smartphone Pro",
    "Price": 850.00
}

Response:

{
    "Id": 2,
    "Name": "Smartphone Pro",
    "Price": 850.00
}

4. DELETE Method

The HTTP DELETE method is used to remove a resource from the server. When a client sends a DELETE request, it specifies the resource to be deleted by including its identifier in the URL. The server processes the request and deletes the resource, returning an appropriate response code.

Use Case: Deleting a product, removing a user account, etc.

Example:

// Controller Action
[HttpDelete]
public IHttpActionResult DeleteProduct(int id)
{
    var product = _productRepository.GetProductById(id);
    if (product == null)
    {
        return NotFound();
    }

    _productRepository.DeleteProduct(id);
    return StatusCode(HttpStatusCode.NoContent);
}

Request: DELETE http://myapi.com/api/products/2 Response: No content returned with status code 204.

Conclusion

GET, POST, PUT, and DELETE methods form the foundation for HTTP communication in ASP.NET Web API. Each method serves a specific purpose, ensuring that clients can correctly interact with server resources. Understanding how to implement and use these methods properly is crucial for building robust and scalable web APIs.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET Web API GET, POST, PUT, DELETE Methods Explained

Step 1: Create a New ASP.NET Web API Project

  1. Open Visual Studio.
  2. Go to File > New > Project.
  3. Select ASP.NET Core Web Application (or ASP.NET Web Application, depending on your .NET version preference) and click Next.
  4. Give your project a name (e.g., WebApiTutorial) and choose the location to save it.
  5. Click Create.
  6. In the next dialog, choose the API template and click Create.

Step 2: Define a Model

Let's define a simple model Product:

using System.ComponentModel.DataAnnotations;

namespace WebApiTutorial.Models
{
    public class Product
    {
        [Key]
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }

        [Range(1, 999999)]
        public decimal Price { get; set; }
    }
}

Step 3: Set Up an In-Memory Data Store

For simplicity, we'll use an in-memory list to store our Product data instead of a database:

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using WebApiTutorial.Models;

namespace WebApiTutorial.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private static readonly List<Product> _products = new List<Product>
        {
            new Product { Id = 1, Name = "Laptop", Price = 999.99m },
            new Product { Id = 2, Name = "Smartphone", Price = 699.99m }
        };

        #region GET
        // GET: api/Products
        [HttpGet]
        public ActionResult<IEnumerable<Product>> GetProducts()
        {
            return _products;
        }

        // GET: api/Products/5
        [HttpGet("{id}")]
        public ActionResult<Product> GetProduct(int id)
        {
            var product = _products.FirstOrDefault(p => p.Id == id);

            if (product == null)
            {
                return NotFound();
            }

            return product;
        }
        #endregion

        #region POST
        // POST: api/Products
        [HttpPost]
        public ActionResult<Product> PostProduct(Product product)
        {
            _products.Add(product);
            product.Id = _products.Count + 1; // Simple ID assignment
            return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
        }
        #endregion

        #region PUT
        // PUT: api/Products/5
        [HttpPut("{id}")]
        public IActionResult PutProduct(int id, Product product)
        {
            var existingProduct = _products.FirstOrDefault(p => p.Id == id);

            if (existingProduct == null)
            {
                return NotFound();
            }

            existingProduct.Name = product.Name;
            existingProduct.Price = product.Price;

            return NoContent(); // Return 204 No Content
        }
        #endregion

        #region DELETE
        // DELETE: api/Products/5
        [HttpDelete("{id}")]
        public IActionResult DeleteProduct(int id)
        {
            var product = _products.FirstOrDefault(p => p.Id == id);

            if (product == null)
            {
                return NotFound();
            }

            _products.Remove(product);

            return NoContent(); // Return 204 No Content
        }
        #endregion
    }
}

Step 4: Test the Endpoints

Now that we have our CRUD methods implemented, we can test them using tools like Postman or directly from a browser (for GET methods).

Testing with Postman

Download and install Postman if you haven't already.

GET All Products

  • Method: GET
  • URL: https://localhost:<port>/api/products

GET Product by ID

  • Method: GET
  • URL: https://localhost:<port>/api/products/1

POST New Product

  • Method: POST
  • URL: https://localhost:<port>/api/products
  • Body:
    {
        "Name": "Headphones",
        "Price": 149.99
    }
    

PUT Update Product

  • Method: PUT
  • URL: https://localhost:<port>/api/products/3
  • Body:
    {
        "Id": 3,
        "Name": "Updated Headphones",
        "Price": 139.99
    }
    

DELETE Product

  • Method: DELETE
  • URL: https://localhost:<port>/api/products/3

Explanation of the Code

GET Method

Top 10 Interview Questions & Answers on ASP.NET Web API GET, POST, PUT, DELETE Methods Explained

1. What is ASP.NET Web API?

Answer: ASP.NET Web API is a framework that enables developers to build HTTP services that can reach a broad range of clients, including browsers and mobile devices. It allows you to easily create RESTful services that can be consumed from the web or from mobile applications.

2. What is the purpose of the GET method in ASP.NET Web API?

Answer: The GET method is used to retrieve data from the server. It is one of the safest and idempotent operations provided by HTTP. When a GET request is made, the server returns the data requested from the specified URL without modifying the resource.

3. How do you handle a GET request in ASP.NET Web API?

Answer: In ASP.NET Web API, handling a GET request involves creating a controller with an action method that returns the requested data. You typically use an HttpGet attribute to explicitly mark this action, although it's optional if the method name starts with "Get". For example:

[HttpGet]
public IHttpActionResult GetUser(int id)
{
    var user = _userRepository.GetUserById(id);
    if (user == null)
    {
        return NotFound();
    }
    return Ok(user);
}

4. What is the difference between GET and POST methods?

Answer: The main difference between GET and POST methods is that GET is used to retrieve data, whereas POST is used to send data to the server to create or update a resource. Data sent with a GET request is appended to the URL, making it less secure for sensitive data, while data sent with a POST request is included in the body of the request.

5. How do you handle a POST request in ASP.NET Web API?

Answer: Handling a POST request involves creating an action method that accepts the data to be created, typically through the body of the request. Here’s a simple example:

[HttpPost]
public IHttpActionResult CreateUser(User user)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var createdUser = _userRepository.CreateUser(user);
    return CreatedAtRoute("DefaultApi", new { id = createdUser.Id }, createdUser);
}

6. What is the PUT method in ASP.NET Web API used for?

Answer: The PUT method is used to update an existing resource on the server. It expects the client to send the entire entity with the new data, allowing the server to replace the existing resource with the new one.

7. How do you handle a PUT request in ASP.NET Web API?

Answer: Handling a PUT request involves creating an action method that accepts the updated data for a specific resource. Here’s how:

[HttpPut]
public IHttpActionResult UpdateUser(int id, User user)
{
    if (!ModelState.IsValid || id != user.Id)
    {
        return BadRequest();
    }

    var updatedUser = _userRepository.UpdateUser(user);
    if (updatedUser == null)
    {
        return NotFound();
    }
    return Ok(updatedUser);
}

8. What is the DELETE method in ASP.NET Web API used for?

Answer: The DELETE method is used to remove a resource from the server. It sends a request to the server indicating which resource should be removed, typically identified by its ID.

9. How do you handle a DELETE request in ASP.NET Web API?

Answer: Handling a DELETE request involves creating an action method that deletes the specified resource. Here is an example:

[HttpDelete]
public IHttpActionResult DeleteUser(int id)
{
    var user = _userRepository.GetUserById(id);
    if (user == null)
    {
        return NotFound();
    }

    _userRepository.DeleteUser(id);
    return StatusCode(HttpStatusCode.NoContent);
}

10. What are the key differences between PUT and PATCH methods?

Answer: Both PUT and PATCH methods are used for updating resources, but they differ in their approach:

  • PUT is used to update entire resources. The client sends the full representation of the resource, and the server replaces the existing resource with the new one.
  • PATCH is used to update part of a resource. The client sends a partial representation of the resource with only the fields that need to be updated, which can be more efficient.

You May Like This Related .NET Topic

Login to post a comment.