ASP.NET Core Web API Fundamentals

Learning Objectives

  • Understand how to create RESTful APIs using ASP.NET Core.
  • Learn about controllers, actions, and attribute routing.
  • Gain insights into ASP.NET Core routing and middleware.
  • Learn how to use Dependency Injection (DI) in ASP.NET Core.

Creating Web APIs

What is a Web API? A Web API (Application Programming Interface) allows different applications to communicate with each other over HTTP. In ASP.NET Core, Web APIs are built using controllers and actions to define endpoints, and attribute routing to manage how requests are directed.

Controllers, Actions, and Attribute Routing

  • Controller: A class that handles incoming HTTP requests and sends responses.
  • Action: A method inside a controller that performs a specific task (like fetching data).
  • Attribute Routing: A way to specify routes using attributes on actions or controllers.

Creating Your First Web API

  1. Step 1: Create a new Web API project in Visual Studio by selecting ASP.NET Core Web API as the template.
  2. Step 2: The generated project will have a default controller called WeatherForecastController.
  3. Step 3: Add a new controller called ProductController to handle product data.

Code Example:

[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
    [HttpGet]
    public IActionResult GetProducts()
    {
        var products = new List<string> { "Laptop", "Phone", "Tablet" };
        return Ok(products);
    }
}

Real-Life Example: In an e-commerce application, the ProductController can serve product listings to customers.

Routing & Middleware

Routing in ASP.NET Core

Routing determines how an incoming request is mapped to a specific controller action. ASP.NET Core supports attribute routing (using attributes in controllers) and conventional routing (defined in Program.cs).

Attribute Routing:

[HttpGet("products/{id}")]
public IActionResult GetProductById(int id)
{
    return Ok($"Product with ID: {id}");
}

This route will match GET requests to /products/{id}.

Conventional Routing:

Defined in Program.cs for common routes.

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

Middleware

Middleware are components that handle requests and responses in the ASP.NET Core pipeline. Middleware are added in Program.cs and are executed in the order in which they are added.

Common Middleware:

  • UseRouting(): Adds route matching to the pipeline.
  • UseAuthentication() and UseAuthorization(): Handles authentication and authorization.

Example of Middleware in Program.cs:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseRouting();
app.UseAuthorization();

app.MapControllers();

app.Run();

Real-Life Example: In a user management system, middleware can be used to log all incoming requests to track user activities for auditing purposes.

Dependency Injection (DI)

What is Dependency Injection? Dependency Injection (DI) is a technique used to improve code modularity and make it more testable by injecting required dependencies instead of instantiating them manually.

ASP.NET Core has a built-in DI container that helps manage service lifetimes:

  1. Transient: Created each time they are requested.
  2. Scoped: Created once per request.
  3. Singleton: Created once and shared throughout the application.

Registering Services:

builder.Services.AddScoped<IProductService, ProductService>();

This registers ProductService with a scoped lifetime, meaning it will be created once per request.

Using DI in a Controller:

public class ProductController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductController(IProductService productService)
    {
        _productService = productService;
    }

    [HttpGet]
    public IActionResult GetProducts()
    {
        var products = _productService.GetAllProducts();
        return Ok(products);
    }
}

Real-Life Example: In a financial application, DI can be used to inject a service that handles transactions, ensuring that each request gets its own instance for consistency.

Key Takeaways

  • Controllers and Actions are essential for creating Web APIs, with attribute routing making it easy to define endpoints.
  • Middleware are used to handle requests and responses in a sequential order.
  • Dependency Injection helps manage dependencies efficiently, promoting code modularity and making testing easier.

Practical Questions

  1. How does attribute routing differ from conventional routing in ASP.NET Core?
  2. What are middleware, and how do they handle requests in an ASP.NET Core application?
  3. How can Dependency Injection improve code quality in an API project?

ניווט במאמר

מאמרים אחרונים

Weekly Tutorial