ASP.NET Core Routing & Controllers 1 — Questions and Answers
Question 1: Which attribute defines a route template directly on an ASP.NET Core controller action?
- [Route] (Correct answer)
- [HttpGet]
- [Path]
- [Endpoint]
Correct answer: [Route]
[Route("path")] sets the route template for a controller or action, and can be combined with HTTP method attributes.
Question 2: What does the [ApiController] attribute do in ASP.NET Core?
- Enables automatic model validation, binding source inference, and problem details responses (Correct answer)
- Registers the controller as a service
- Disables view rendering
- Enforces JSON-only responses
Correct answer: Enables automatic model validation, binding source inference, and problem details responses
[ApiController] opts the controller into API-specific conventions like automatic 400 responses on validation failure.
Question 3: What route token represents an action name in a conventional route template?
- {action} (Correct answer)
- [action]
- <action>
- $(action)
Correct answer: {action}
{action} is the conventional route token that maps to the action method name in the default MVC route template.
Question 4: Which return type enables ASP.NET Core Web API actions to return multiple response types with proper metadata?
- IActionResult or ActionResult<T> (Correct answer)
- Task<object>
- HttpResponseMessage
- JsonResult only
Correct answer: IActionResult or ActionResult<T>
ActionResult<T> allows returning both a typed result and different HTTP status code responses, enabling OpenAPI documentation.
Question 5: What is the purpose of [HttpGet("{id}")] on an action method?
- It constrains the action to GET requests and captures an 'id' route parameter (Correct answer)
- It filters GET requests by ID in the query string only
- It generates an ID automatically
- It maps the action to a service by ID
Correct answer: It constrains the action to GET requests and captures an 'id' route parameter
Combining the HTTP method attribute with a template restricts the HTTP verb and defines the route in one declaration.
Question 6: What method is called to add MVC controllers with views in ASP.NET Core?
- services.AddControllersWithViews() (Correct answer)
- services.AddMvc()
- services.AddControllers()
- services.AddViewControllers()
Correct answer: services.AddControllersWithViews()
AddControllersWithViews() registers controllers plus Razor view support, whereas AddControllers() registers controllers for APIs only.
Which attribute defines a route template directly on an ASP.NET Core controller action?