ASP.NET Core Interview Question #125
What are best practices for routing, controllers, and model binding in ASP.NET Core?
Routing, Controllers & Model Binding Mid-Level Intermediate
Quick Interview Answer
Design routes to be stable, readable, and unambiguous. Use route constraints where they improve matching, and choose conventional or attribute routing according to the application's URL requirements.
Detailed Explanation
Design routes to be stable, readable, and unambiguous. Use route constraints where they improve matching, and choose conventional or attribute routing according to the application's URL requirements.
Keep controllers thin: accept HTTP input, validate the request contract, call application services, and return an appropriate result. Do not place large amounts of business logic or data-access code directly in controller actions.
Use dedicated ViewModels or DTOs for input instead of binding persistence entities directly. Validate input, protect state-changing browser requests against CSRF where applicable, use correct HTTP methods and status codes, and keep public endpoint contracts explicit.
Code Example
[HttpPost("products")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ProductCreateViewModel model)
{
if (!ModelState.IsValid)
return View(model);
await _productService.CreateAsync(model);
return RedirectToAction(nameof(Index));
}