Routing in ASP.NET Core MVC
Routing = Maps URL requests to controller actions. It's the GPS that tells a request where to go in your C# code.
60-Second Version: Use
[Route] attributes. Put specific routes first. [HttpGet("products/{id:int}")] handles GET /products/5. Constraints like :int filter bad URLs. Never hardcode href="/products/5" - use asp-route-id="5".1. Attribute Routing: The Only Way That Matters
Put routes directly on controllers and actions. This is required for Web APIs and best for MVC.
[Route("products")]
public class ProductsController : Controller
{
[HttpGet] // GET /products
public IActionResult Index() => View();
[HttpGet("{id:int}")] // GET /products/5
public IActionResult Details(int id) => View();
[HttpPost] // POST /products from form
public IActionResult Create(ProductViewModel vm) { }
}
2. Route Constraints = Input Validation for URLs
Stops /products/abc from crashing your int id action.
| Constraint | Example | Blocks |
|---|---|---|
:int | {id:int} | "abc", 12.5 |
:guid | {id:guid} | 123, "hello" |
:alpha | {slug:alpha} | 123, "hello-1" |
:minlength(3) | {name:minlength(3)} | "ab" |
3. HTTP Verbs: GET, POST, PUT, DELETE
[HttpGet("products")] // List all
[HttpGet("products/{id}")] // Get one
[HttpPost("products")] // Create new
[HttpPut("products/{id}")] // Update existing
[HttpDelete("products/{id}")] // Remove
Rule: Forms use GET/POST. APIs use all 4. If you forget [HttpPost], your form gets 405 Method Not Allowed.
4. Route Order: Specific โ General
First match wins. Put /blog/archive/{year} before /blog/{slug} or "archive" becomes a slug.
Beginner Trap: Rohan forgets
[HttpPost] on Create action. Form submits, gets 404. Or he uses [Route("{id}")] and [Route("{slug}")] on same controller = AmbiguousMatchException. Fix: Add :int to id route.
Quick Check ๐ง
Next: Views & Razor in MVC - @model, layouts, _ViewStart, partials, and rendering HTML.
No comments yet. Be the first to share your thoughts!