In this lesson, you will learn how to build expressive, SEO-friendly URL structures in your Razor Pages by using routing templates and precise constraints.
Understanding Route Templates
By default, Razor Pages derive their URL from the file path within the Pages folder. However, real-world applications often require cleaner, more descriptive URLs. You can override the default convention by using the @page directive followed by a route template.
For example, if you have a product details page, rather than /Products/Details?id=5, you can define an expressive route:
@page "/products/{id:int}"
This tells the routing engine that any request matching this pattern should be directed to this page, automatically mapping the segment to a variable named id.
Applying Route Constraints
Route constraints act as a "gatekeeper" for your URLs, ensuring that only requests with the correct data types reach your logic. Without them, an invalid URL like /products/abc might attempt to bind abc to an integer property, leading to unnecessary 404 errors or model state validation failures.
By adding constraints directly to the template, you validate the request at the infrastructure level:
{id:int}: Ensures the segment is a valid integer.{slug:alpha}: Ensures the segment contains only alphabetic characters.{id:range(1, 1000)}: Restricts the integer to a specific numeric range.
Why This Matters
Using these patterns provides two major benefits:
- SEO Optimization: Search engines prefer human-readable URLs like
/blog/why-csharp-is-greatover query strings like?id=123. - Robustness: Constraints prevent malformed requests from reaching your controller or page model code, allowing you to prioritize clean, valid data flow.
If a request hits a URL that doesn't meet the constraints (e.g., a user visits /products/missing-data), the routing engine will automatically skip this route, allowing you to handle the 404 gracefully or provide a fallback route elsewhere in your application.
Key Takeaway: Route constraints allow you to enforce strict data validation directly in your URL schema, creating predictable, cleaner, and search-engine-optimized navigation for your users.