Chapter 5: Routing Basics in C#

Static routes and the trie router explained. In this chapter, you will learn routing basics in depth with C# code examples, explanations, and best practices.

Overview

This chapter covers routing basics for Kungfu.js developers using C#. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.

Why This Matters

Understanding routing basics is essential because it is a core part of building web applications. Every real-world app needs to handle static routes and the trie router explained. Skipping this chapter would leave a gap in your knowledge that would cause problems later.

Code Example

Here is how routing works in C#:

// Static route
app.get('/', (req) => { ... });

// Path parameter: /users/42
app.get('/users/:id', (req) => {
    const id = req.param('id'); // "42"
});

// Wildcard: /assets/css/app.css
app.get('/assets/*path', (req) => {
    const path = req.param('path'); // "css/app.css"
});

// Query string: /search?q=rust&limit=10
app.get('/search', (req) => {
    const q = req.query('q'); // "rust"
    const limit = req.query('limit'); // "10"
});

How It Works

The router uses a trie data structure. Each segment of the URL path becomes a node in the tree. When a request comes in, the router walks the tree segment by segment. This is much faster than checking every route one by one.

For example, if you register /users/:id and a request comes in for /users/42, the router:

  1. Starts at the root node
  2. Moves to the "users" child node
  3. Sees a parameter node ":id" and captures "42" as the id parameter
  4. Calls your handler with req.param("id") equal to "42"

Common Mistakes

  • Not reading the documentation: Always check the API reference when something does not work as expected.
  • Skipping security: Never disable the default middleware unless you have a very good reason. Security is not optional.
  • Not testing: Write tests for your handlers. Kungfu.js makes this easy with the built-in test utilities.

Summary

In this chapter, you learned about routing basics in C#. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.

What is Next?

In chapter 6, we will cover Path Parameters: Capture dynamic values from URLs.