ASP.NET Core Routing & Controllers 2 — Questions and Answers
Question 1: Which attribute binds an action parameter from the URL route data?
- [FromRoute] (Correct answer)
- [FromQuery]
- [FromBody]
- [FromHeader]
Correct answer: [FromRoute]
[FromRoute] explicitly binds the parameter value from route template tokens rather than other sources.
Question 2: What does app.MapControllers() do in the minimal hosting model?
- Maps attribute-routed controller endpoints to the routing system (Correct answer)
- Scans for controllers and registers them as services
- Adds conventional routes for all controllers
- Enables model binding on all controllers
Correct answer: Maps attribute-routed controller endpoints to the routing system
MapControllers() registers attribute-routed controllers as endpoints without requiring conventional routes.
Question 3: How do you make a route parameter optional in ASP.NET Core attribute routing?
- Add a ? after the parameter name: {id?} (Correct answer)
- Use [Optional] on the parameter
- Set the parameter default to null in the route
- Use {id:optional}
Correct answer: Add a ? after the parameter name: {id?}
Appending ? to a route token like {id?} marks it optional, allowing the route to match URLs with or without the segment.
Question 4: Which helper method creates a 201 Created response with a Location header in an API controller?
- CreatedAtAction() (Correct answer)
- Ok()
- Created()
- StatusCode(201)
Correct answer: CreatedAtAction()
CreatedAtAction() generates the Location header by routing to the specified action, following REST conventions for POST.
Question 5: What does [Bind] attribute do on a model class in ASP.NET Core MVC?
- Restricts which properties are included during model binding (Correct answer)
- Forces all properties to be required
- Disables model binding for the class
- Binds the model to a specific data source
Correct answer: Restricts which properties are included during model binding
[Bind("Prop1,Prop2")] whitelists only the specified properties, preventing over-posting security vulnerabilities.
Question 6: Which route constraint restricts a route parameter to integer values only?
- {id:int} (Correct answer)
- {id:integer}
- {id=int}
- {id[int]}
Correct answer: {id:int}
The :int route constraint ensures the segment matches only integer values, rejecting non-numeric requests at routing time.
Which attribute binds an action parameter from the URL route data?