Skip to main content

Controllers and Actions in .NET Core with an Item API

 

In .NET Core, the concepts of controllers and actions form the backbone of handling HTTP requests in a web application. Controllers serve as intermediaries between the user interface and the data model, while actions are the methods within these controllers that handle the specific requests. This blog will explore these concepts using a simple Item API as an example, along with detailed C# code snippets.

What is a Controller?

A controller in .NET Core is a class that is responsible for handling incoming HTTP requests and returning appropriate responses. It serves as the decision-maker that orchestrates how a request should be processed. Each controller class typically represents a specific part of your application, such as "Items" in an inventory management system.

What is an Action?

An action is a method within a controller that handles a specific HTTP request. For example, an action might retrieve an item from a database, create a new item, or delete an item. Actions are usually associated with HTTP verbs like GET, POST, PUT, DELETE, etc., which correspond to the standard CRUD (Create, Read, Update, Delete) operations.

Creating an Item API: Step-by-Step

Let's walk through creating a simple Item API that handles basic CRUD operations.

1. Setting Up the Controller

First, let's create a controller named ItemsController. In a .NET Core web API, controllers usually inherit from ControllerBase or Controller. For APIs, ControllerBase is sufficient since it doesn't include view support, which is unnecessary for APIs.

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

namespace ItemApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ItemsController : ControllerBase
    {
        private static List<Item> Items = new List<Item>
        {
            new Item { Id = 1, Name = "Item1", Description = "First item" },
            new Item { Id = 2, Name = "Item2", Description = "Second item" },
        };

        // Actions will go here
    }
}

Here, we define a static list of Item objects that will act as our in-memory data store. In a real-world application, you would interact with a database.

2. Creating the Item Model

Before diving into the actions, we need to define the Item model, which represents the structure of the data we're working with.

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

This simple model includes an Id, Name, and Description for each item.

3. Implementing CRUD Actions

Now, let's implement the various actions that will handle CRUD operations.

GET: Retrieve All Items

The first action will handle a GET request to retrieve all items.

[HttpGet]
public ActionResult<IEnumerable<Item>> GetItems()
{
    return Ok(Items);
}

This action returns an IEnumerable<Item> wrapped in an ActionResult, which provides flexibility in returning different HTTP status codes if necessary. Here, we're simply returning an Ok response with the list of items.

GET: Retrieve a Single Item by ID

Next, let's create an action to retrieve a single item by its Id.

[HttpGet("{id}")]
public ActionResult<Item> GetItem(int id)
{
    var item = Items.FirstOrDefault(i => i.Id == id);
    if (item == null)
    {
        return NotFound();
    }
    return Ok(item);
}

This action uses a route parameter to identify the specific item. If the item is not found, it returns a NotFound response; otherwise, it returns the item.

POST: Create a New Item

Now, let's add an action to create a new item.

[HttpPost]
public ActionResult<Item> CreateItem(Item item)
{
    item.Id = Items.Max(i => i.Id) + 1; // Simulate auto-increment
    Items.Add(item);
    return CreatedAtAction(nameof(GetItem), new { id = item.Id }, item);
}

The CreateItem action accepts an Item object, assigns it a new Id, adds it to the list, and returns a CreatedAtAction response, which includes the URI of the newly created item.

PUT: Update an Existing Item

To update an existing item, we can use the PUT method.

[HttpPut("{id}")]
public ActionResult UpdateItem(int id, Item updatedItem)
{
    var item = Items.FirstOrDefault(i => i.Id == id);
    if (item == null)
    {
        return NotFound();
    }

    item.Name = updatedItem.Name;
    item.Description = updatedItem.Description;

    return NoContent(); // 204 status code
}

The UpdateItem action locates the item by its Id, updates its properties, and returns a NoContent response to indicate the update was successful.

DELETE: Remove an Item

Finally, let's implement the DELETE action.

[HttpDelete("{id}")]
public ActionResult DeleteItem(int id)
{
    var item = Items.FirstOrDefault(i => i.Id == id);
    if (item == null)
    {
        return NotFound();
    }

    Items.Remove(item);
    return NoContent();
}

This action removes the item with the specified Id from the list and returns a NoContent response.

Conclusion

In this blog, we've explored the basics of controllers and actions in .NET Core using a simple Item API as an example. Controllers act as the main entry point for handling requests, and actions within these controllers correspond to specific HTTP operations. By following the above steps, you can create a robust API that handles CRUD operations efficiently.

Whether you're building a small application or a large-scale enterprise solution, understanding and properly implementing controllers and actions is crucial for managing HTTP requests effectively.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...