Routing in ASP.NET Core.

Routing is a fundamental concept in ASP.NET Core that enables the framework to map incoming HTTP requests to specific endpoints in your application. It plays a crucial role in defining how URLs are structured and how they correspond to the actions in your application. This article will provide a detailed overview of routing in ASP.NET Core, including its types, configuration, and examples.

What is Routing?

Routing is the process of directing an incoming HTTP request to the appropriate handler based on the URL and HTTP method. In ASP.NET Core, routing is handled by the middleware, which inspects the request and matches it against defined routes.

Which Middleware Handles Routing?

In ASP.NET Core, routing is handled by two key middleware components:

1. UseRouting() Middleware

  • Purpose: Matches the incoming HTTP request to the route template (defined via MapControllerRoute, attribute routing, etc.).
  • Placement: Must come before UseAuthorization() and UseEndpoints()

2. UseEndpoints() Middleware
  • Purpose: Executes the matched route handler (e.g., controller action, Razor page, minimal API).
  • It finalizes the routing decision made by UseRouting().

Types of Routing

ASP.NET Core supports two main types of routing:

  • Convention-based Routing: This is the default routing mechanism that uses predefined patterns to match incoming requests. It is typically used in MVC applications.
  • Attribute Routing: This allows developers to define routes directly on the controller actions using attributes. This method provides more control and flexibility over the routing configuration.

Key Note:
  • MapControllers(): Enables attribute routing ([Route("api/[controller]")])
  • MapControllerRoute(): Enables convention-based routing (like {controller}/{action}/{id?})

Convention-Based Routing in ASP.NET Core

Convention-based routing follows a predefined pattern to map incoming URLs to controller actions. This routing logic is configured centrally, usually in the Program.cs or Startup.cs file.

It's called “convention-based” because your app follows naming conventions for controllers, actions, and parameters to match the routes.

How to configure (Program.cs):
var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllersWithViews(); // For MVC
builder.Services.AddControllers(); // For Web API

var app = builder.Build();

// Configure the HTTP request pipeline
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

// Configure endpoints
app.UseEndpoints(endpoints =>
{
    // MVC Routing
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    // API Routing (attribute routing will be used)
    endpoints.MapControllers();
});

app.Run();
  • controller=Home: default controller
  • action=Index: default action
  • id?: optional parameter

Example:
public class ProductsController : Controller
{
    public IActionResult Details(int id)
    {
        return View(); // Returns View for /products/details/5
    }
}

Request:
GET /products/details/5

Matched By Pattern:
{controller=Products}/{action=Details}/{id=5}

Benefits of Convention-Based Routing:
  • Centralized route definitions
  • Easier to manage in large MVC apps
  • Reduces redundancy

Limitations:
  • Less flexible for APIs
  • It can become confusing with too many controllers/actions

Attribute Routing in ASP.NET Core

Attribute routing uses attributes directly on controller classes and action methods to define the routing rules. This provides more control and makes the routing explicit and readable.

Introduced in ASP.NET Web API and now standard in ASP.NET Core.

How To Use:
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAll()
    {
        return Ok("All Products");
    }

    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        return Ok($"Product {id}");
    }

    [HttpPost]
    public IActionResult Create(Product product)
    {
        return Ok("Product Created");
    }
}

Request:

URL Method Action Called
GET /api/products [HttpGet] GetAll()
GET /api/products/2 [HttpGet("{id}")] GetById(2)
POST /api/products [HttpPost] Create()

Benefits of Attribute Routing:
  • Better suited for RESTful APIs
  • Greater clarity and control per action
  • Easy to document and maintain

How To Pass Multiple Values in a Request?

There are multiple ways to pass more than one parameter in a Request. Let's discuss each of them one by one:

1. Pass via Query String.
Query parameters are used to send data to the server in a key-value format. For example, in the URL:
https://localhost:5001/api/products?category=electronics&sort=price
The query parameters are category and sort, with values electronics and price, respectively.

You can access query parameters in your controller actions without needing to define them in the route. Here’s how you can do it:

Example of Using Query Parameters:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    private static readonly List<Product> _products = new()
    {
        new Product(1, "Laptop", 999.99m, "electronics"),
        new Product(2, "Mouse", 25.50m, "accessories"),
        new Product(3, "Smartphone", 699.99m, "electronics")
    };

    [HttpGet]
    public IActionResult Get([FromQuery] string category, [FromQuery] string sort)
    {
        var products = _products.AsQueryable();

        if (!string.IsNullOrEmpty(category))
        {
            products = products.Where(p => p.Category == category);
        }

        if (sort == "price")
        {
            products = products.OrderBy(p => p.Price);
        }

        return Ok(products.ToList());
    }
}

2. Pass Multiple values via Route Parameters.
In ASP.NET Core, you can pass multiple values via route parameters by defining them in the route template. This allows you to capture multiple segments of the URL as parameters in your controller action. Here’s how to do it:

To get a product by category and ID:
GET https://localhost:5001/api/products/electronics/1

Example of Using Query Parameter:
using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    // Sample data
    private static readonly List<Product> _products = new()
    {
        new Product(1, "Laptop", "electronics"),
        new Product(2, "Mouse", "accessories"),
        new Product(3, "Smartphone", "electronics")
    };

    // Action method to get product by category and ID
    [HttpGet("{category}/{productId}")]
    public IActionResult GetProduct(string category, int productId)
    {
        var product = _products.FirstOrDefault(p => p.Id == productId && p.Category == category);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
}

public record Product(int Id, string Name, string Category);

Bonus: For PUT/POST requests, we usually send JSON data in the body.
{
  "name": "Laptop",
  "price": 1500,
  "category": "Electronics"
}

Example Controller Action Method:
[HttpPost]
public IActionResult AddProduct([FromBody] Product product)
{
    // Access product.Name, product.Price, etc.
    return Ok($"Added: {product.Name}");
}

Note: You can only bind one complex object from the body using [FromBody]. If you need to pass multiple complex objects, wrap them into a single class.

Conclusion.

Understanding how routing works in ASP.NET Core Web API, especially the use of HTTP methods like GET, POST, and the power of attribute routing is essential for building clean, scalable, and RESTful services. By mapping specific URLs to controller actions using clear route definitions, you ensure that your API is both intuitive and maintainable

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS