09 التوجية و الأحداث في كور ويب Routing and actions in ASP .NET Core

3 min read 2 hours ago
Published on Oct 12, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial provides a comprehensive guide on routing and actions in ASP.NET Core, as discussed in Ahmed Mohamady's video. Understanding these concepts is essential for developing web applications using ASP.NET Core, as they govern how HTTP requests are handled and directed within your application.

Step 1: Understanding Routing in ASP.NET Core

Routing is the process that maps HTTP requests to the appropriate action methods in your application. Here’s how to get started:

  • Default Routing: By default, ASP.NET Core uses conventional routing. It follows a pattern like this:

    /{controller=Home}/{action=Index}/{id?}
    
    • Controller: The name of the controller class without the suffix "Controller".
    • Action: The method inside the controller that responds to the request.
    • Id: An optional parameter.
  • Configuring Routes: To customize routes, you can define them in the Startup.cs file within the Configure method:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
    

Step 2: Creating Action Methods

Action methods are responsible for processing requests and returning responses. Follow these steps to create action methods in your controller:

  • Define a Controller: Create a new controller class in the Controllers folder:

    public class HomeController : Controller
    {
        // Action Method
        public IActionResult Index()
        {
            return View();
        }
    
        public IActionResult About()
        {
            return View();
        }
    }
    
  • Return Types: Action methods can return various types:

    • IActionResult: A common return type that can represent various HTTP responses.
    • ViewResult: Returns a view to the user.
    • JsonResult: Returns JSON formatted data.

Step 3: Handling Parameters in Action Methods

Action methods can accept parameters directly from the URL:

  • Route Parameters: You can declare parameters in the action method which will map directly from the URL:

    public IActionResult Details(int id)
    {
        // Use id to fetch data
        return View();
    }
    

    Accessing a URL like /Home/Details/5 will set id to 5.

  • Query Strings: You can also access parameters via query strings:

    public IActionResult Search(string query)
    {
        // Process search
        return View();
    }
    

    This allows users to search with URLs like /Home/Search?query=example.

Step 4: Implementing Action Filters

Action filters allow you to execute code before or after action methods. Here’s how to implement them:

  • Creating a Custom Action Filter:
    public class MyActionFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            // Code before action executes
        }
    
        public void OnActionExecuted(ActionExecutedContext context)
        {
            // Code after action executes
        }
    }
    
  • Registering the Filter: You can register the filter globally or at the controller/action level in your Startup.cs or directly in your controller.

Step 5: Using Attribute Routing

ASP.NET Core also supports attribute routing, which allows you to specify routes directly on action methods:

  • Define Routes Using Attributes:
    [Route("home")]
    public class HomeController : Controller
    {
        [Route("index")]
        public IActionResult Index()
        {
            return View();
        }
        
        [Route("about")]
        public IActionResult About()
        {
            return View();
        }
    }
    
    With this setup, you can access the actions via /home/index and /home/about.

Conclusion

In this tutorial, we covered the essentials of routing and actions in ASP.NET Core, including how to set up routes, create action methods, handle parameters, implement action filters, and utilize attribute routing.

To enhance your skills further, consider exploring more about middleware and dependency injection in ASP.NET Core. Happy coding!