C# / C# Web Development with ASP.NET

Understanding Routing and Controllers

This tutorial delves into the concepts of routing and controllers in ASP.NET. You'll learn how to define routes and create controllers to handle user requests and return responses.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Introduces web development using ASP.NET for creating dynamic web applications.

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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Image Converter

Convert between different image formats.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help