Understanding Routing and Controllers

Tutorial 3 of 5

Understanding Routing and Controllers in ASP.NET

1. Introduction

Brief explanation of the tutorial's goal

This tutorial aims to help you understand the fundamentals of routing and controllers in ASP.NET. By the end of this tutorial, you should be able to define routes and create controllers that handle user requests and return responses.

What the user will learn

  • What routing and controllers are in ASP.NET
  • How to define routes
  • How to create controllers

Prerequisites

  • Basic knowledge of ASP.NET
  • Installed .NET SDK and a code editor like Visual Studio or Visual Studio Code

2. Step-by-Step Guide

Detailed explanation of concepts

  1. Routing: Routing is a mechanism in ASP.NET that decides which action method of a controller class to execute. It maps URL routes to specific controllers and action methods.

  2. Controllers: Controllers are classes in ASP.NET MVC that respond to HTTP requests. They determine what action to take, handle user input, work with models, and select a view to render that displays UI.

Clear examples with comments

  1. Defining Routes: In the Startup.cs file, the Configure() method sets up the application's routes. Here's a basic example:
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

In this example, the pattern {controller=Home}/{action=Index}/{id?} defines a default route where Home is the default controller, Index is the default action, and id is an optional parameter.

  1. Creating Controllers: Controllers are located in the Controllers folder. Here's an example of a basic HomeController:
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

This HomeController has an Index action method that returns a view.

Best practices and tips

  • Keep your controllers lean. Controllers should only contain actions.
  • Use the [Route] attribute for more control over your routes.
  • Name your action methods clearly and descriptively.

3. Code Examples

Multiple practical examples

  1. Custom Route

Here's how to define a custom route:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "blog",
        pattern: "blog/{year}/{month}/{day}",
        defaults: new { controller = "Blog", action = "Post" });
});

This route will match URLs like /blog/2022/10/01 and map them to the Post action method of the Blog controller.

  1. Attribute Routing

Here's an example of attribute routing in a controller:

[Route("api/[controller]")]
public class OrdersController : Controller
{
    [HttpGet("{id}")]
    public IActionResult GetOrder(int id)
    {
        // Fetch and return the order with the specified id
    }
}

In this example, the [Route] attribute specifies the controller's route, and the [HttpGet] attribute specifies the route of the action method.

Expected output or result

These code snippets don't produce a visual output, but they set up the routing and control flow of an ASP.NET application.

4. Summary

Key points covered

  • Routing in ASP.NET maps URLs to controllers and action methods.
  • Controllers respond to HTTP requests and handle the application's control flow.

Next steps for learning

  • Learn about action results in ASP.NET.
  • Understand how to work with views and models in the MVC pattern.

Additional resources

5. Practice Exercises

1. Define a custom route for a Products controller that maps the URL /products/{category} to an action method Category.

2. Create a UsersController with an action method Profile that responds to the URL /users/profile/{username}.

3. Use attribute routing to create a PostsController that includes action methods for creating, reading, updating, and deleting blog posts.

Solutions with explanations

  1. The route can be defined as follows:
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "productCategory",
        pattern: "products/{category}",
        defaults: new { controller = "Products", action = "Category" });
});
  1. The UsersController can be created like this:
public class UsersController : Controller
{
    [Route("users/profile/{username}")]
    public IActionResult Profile(string username)
    {
        // Fetch and return the profile of the specified user
    }
}
  1. The PostsController can be defined using attribute routing as follows:
[Route("api/[controller]")]
public class PostsController : Controller
{
    [HttpPost]
    public IActionResult Create(Post post)
    {
        // Create a new post
    }

    [HttpGet("{id}")]
    public IActionResult Read(int id)
    {
        // Fetch and return the post with the specified id
    }

    [HttpPut("{id}")]
    public IActionResult Update(int id, Post post)
    {
        // Update the post with the specified id
    }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        // Delete the post with the specified id
    }
}

Tips for further practice

  • Try defining more complex routes with multiple parameters.
  • Create controllers with more action methods and use different HTTP methods.