What is Routing in ASP.NET Core? See Example

Routing in ASP.NET Core is the process of mapping incoming HTTP requests to corresponding endpoints, such as controllers, Razor Pages, or middleware. It allows developers to define URL patterns and determine how requests are handled in the application.

Key Features:

  • Maps URLs to controllers, actions, or Razor Pages
  • Supports attribute routing and conventional routing
  • Flexible route templates with parameters
  • Works with MVC, Razor Pages, and APIs
  • Enables clean and SEO-friendly URLs

Example:
Conventional routing in Program.cs:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

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

app.Run();

Attribute routing in a controller:

[Route("products")]
public class ProductController : Controller
{
    [HttpGet("{id}")]
    public IActionResult Details(int id)
    {
        return Content($"Product ID: {id}");
    }
}

Routing is essential in ASP.NET Core for handling requests efficiently and creating user-friendly, structured URLs.

Citations:

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *