Routing in ASP.NET Core determines how HTTP requests map to controller actions. In this blog, we’ll walk through a wide range of routing scenarios—from simple custom routes to attribute-based routing for Web APIs. All examples are compatible with .NET Core 6.0, 7.0, and 8.0.
Map a custom URL to a controller and action:
app.MapControllerRoute(
name: "aboutus",
pattern: "about",
defaults: new { controller = "Info", action = "About" }
);
Effect: Navigating to /about
will call the About()
action in InfoController
.
app.MapControllerRoute(
name: "blogpost",
pattern: "blog/{id:int}",
defaults: new { controller = "Blog", action = "Details" }
);
This defines a route that accepts an integer ID. Example: /blog/10
app.MapControllerRoute(
name: "productDetails",
pattern: "store/products/{category}/{id?}",
defaults: new { controller = "Product", action = "Show" }
);
Supports optional parameters like /store/products/electronics
or /store/products/electronics/101
.
app.MapControllerRoute(
name: "news",
pattern: "news/{category?}",
defaults: new { controller = "News", action = "Index", category = "general" }
);
If no category is specified, general
is used as default.
app.MapControllerRoute(
name: "yearArchive",
pattern: "archive/{year:int:min(2000):max(2025)}",
defaults: new { controller = "Archive", action = "ByYear" }
);
Valid only for years between 2000 and 2025.
app.MapControllerRoute(
name: "seoRoute",
pattern: "articles/{title}-{id:int}",
defaults: new { controller = "Article", action = "Read" }
);
This allows URLs like /articles/aspnet-routing-101-5
.
[Route("home")]
public class HomeController : Controller
{
[Route("welcome")]
public IActionResult Welcome() => Content("Welcome to Home!");
}
URL: /home/welcome
[Route("products")]
public class ProductController : Controller
{
[Route("{id:int}")]
public IActionResult Details(int id) => Content($"Product ID: {id}");
}
[Route("reports/{year:int?}/{month:int?}")]
public IActionResult ByDate(int year = 2025, int month = 1)
{
return Content($"Year: {year}, Month: {month}");
}
[Route("[controller]/[action]")]
public class ProfileController : Controller
{
public IActionResult Info() => Content("This is the profile info");
}
This maps to /profile/info
.
[Route("api/products")]
[ApiController]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll() => Ok("All products");
[HttpGet("{id:int}")]
public IActionResult GetById(int id) => Ok($"Product {id}");
}
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
[ApiController]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetV1() => Ok("API V1");
}
Contact Sudipto Kumar Mukherjee – Microsoft Certified Trainer with 20+ years of experience in .NET, C#, ASP.NET Core.