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.
Section overview
5 resourcesIntroduces 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
-
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.
-
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
- Defining Routes: In the
Startup.csfile, theConfigure()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.
- 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
- 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.
- 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
- The route can be defined as follows:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "productCategory",
pattern: "products/{category}",
defaults: new { controller = "Products", action = "Category" });
});
- The
UsersControllercan 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
}
}
- The
PostsControllercan 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article