ASP.NET Core Web API -

Controllers

ASP.NET Core Web API controllers are responsible for handling incoming HTTP requests and sending responses back to the client. This tutorial covers all you need to know about controllers, from basics to advanced concepts.


What is a Web API Controller?

In ASP.NET Core, a Web API controller is a class that handles HTTP requests and responses. Controllers are derived from ControllerBase and can contain actions that perform operations on data and return responses.

        
            
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class SampleController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok("Hello, World!");
    }
}
        
    

Routing to Controllers

Routing in ASP.NET Core is responsible for mapping incoming requests to action methods in controllers. This section explores how routing works and how to define routes using attributes.

        
            
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet("{id:int}")]
    public IActionResult GetProduct(int id)
    {
        // Logic to retrieve a product by id
        return Ok(new { Id = id, Name = "Sample Product" });
    }
}
        
    

Action Results and Response Types

Controllers can return various types of action results that represent different HTTP responses. Understanding these results is crucial for effective API development.

        
            
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ResponseController : ControllerBase
{
    [HttpGet("[action]")]
    public IActionResult GetNotFound()
    {
        return NotFound();  // Returns a 404 Not Found response
    }

    [HttpGet("[action]")]
    public ActionResult<string> GetBadRequest()
    {
        return BadRequest("Invalid request");  // Returns a 400 Bad Request response
    }

    [HttpGet("[action]")]
    public ActionResult<IEnumerable<string>> GetOk()
    {
        var data = new List<string> { "value1", "value2" };
        return Ok(data);  // Returns a 200 OK response with data
    }
}
        
    

Handling Requests

Handling requests involves receiving data, processing it, and returning responses. Learn about model binding, data validation, and handling complex scenarios in API development.

        
            
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
    [HttpPost]
    public IActionResult Post([FromBody] UserInputModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        // Process the data (save/update)
        return CreatedAtAction("Get", new { id = model.Id }, model);
    }
}

public class UserInputModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    [Required]
    public string Email { get; set; }
}
        
    

Advanced Controller Techniques

Advanced techniques include handling file uploads, asynchronous operations, and using action filters to run code before or after controller actions.


Best Practices for API Controllers

Following best practices in controller design enhances the maintainability, readability, and functionality of your Web API.


Conclusion

Mastering ASP.NET Core Web API controllers is a crucial step towards building robust and scalable web applications. By understanding and implementing the concepts discussed in this tutorial, developers can effectively manage request handling, data processing, and response sending in their applications.