How to use and configure routing in ASP .NET 8?

 Routing in ASP.NET 8 is used to define how URL requests are mapped to controller actions or Razor pages. ASP.NET Core uses endpoint routing, which provides a unified approach to handling routes for MVC, Razor Pages, and other endpoint types. Here’s a comprehensive guide on how to use and configure routing in ASP.NET 8:

Configuring Routing in ASP.NET 8

  1. Basic Routing Setup:

    • Routing is typically configured in the Program.cs file using the MapControllerRoute, MapRazorPages, or MapEndpoints methods.
    csharp

    var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); app.Run();

1. Routing in MVC

Defining Routes in MVC

  • Default Route:

    • The default route pattern is {controller=Home}/{action=Index}/{id?}.
    csharp

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

    • You can define custom routes as needed.
    csharp

    app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "blog", pattern: "blog/{articleId:int}", defaults: new { controller = "Blog", action = "Article" }); });

Controller Actions

  • Define actions in controllers to handle routes.

    csharp

    public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { return View(); } public IActionResult Article(int articleId) { // Fetch and display the article return View(); } }

2. Routing in Razor Pages

Basic Razor Pages Routing

  • Automatic Routing:

    • Razor Pages automatically map URLs to Razor files in the Pages directory.
    csharp

    app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
  • Custom Routes:

    • You can customize routes using the @page directive.
    html

    @page "/custom-route" @model YourNamespace.Pages.CustomPageModel <h1>Custom Route Page</h1>

PageModel Class

  • Define the PageModel class for the Razor Page.

    csharp

    public class CustomPageModel : PageModel { public void OnGet() { // Handle GET request } }

3. Attribute Routing

  • Attribute routing allows you to define routes directly on controller actions.

Using Attribute Routing

  • Controller Actions:

    csharp

    [Route("products")] public class ProductsController : Controller { [Route("")] [Route("index")] public IActionResult Index() { return View(); } [Route("{id:int}")] public IActionResult Details(int id) { // Fetch product by id return View(); } }
  • Route Prefix:

    csharp

    [Route("admin")] [Route("[controller]")] public class AdminController : Controller { [Route("dashboard")] public IActionResult Dashboard() { return View(); } }

4. Advanced Routing Features

Route Constraints

  • Define constraints to restrict route parameters.

    csharp

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

Route Data Tokens

  • Data tokens provide additional data for routes.

    csharp

    app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "areaRoute", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}", defaults: new { area = "Admin" }); });

Route Prioritization

  • Define the order of routes to handle priorities.

    csharp

    app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "blog", pattern: "blog/{articleId:int}", defaults: new { controller = "Blog", action = "Article" }); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });

Summary

  • Basic Configuration: Set up routing in Program.cs using UseRouting and UseEndpoints.
  • MVC Routing: Use MapControllerRoute for defining routes to controllers.
  • Razor Pages Routing: Use MapRazorPages for automatic routing to Razor Pages.
  • Attribute Routing: Define routes using attributes directly on controller actions.
  • Advanced Features: Use constraints, data tokens, and route prioritization for more control.

By following these guidelines, you can effectively configure and use routing in ASP.NET 8 to manage URL requests and map them to the appropriate handlers in your application.

Post a Comment