ASP.NET Core MVC Interview Question #140
How should 404 errors be handled in MVC?
Dependency Injection, Services, Error Handling, Logging & Performance Senior Advanced
Quick Interview Answer
A controller can return NotFound when a requested resource does not exist. The application may also configure status-code pages so unmatched routes and other 404 responses display a consistent user-facing page.
Detailed Explanation
A controller can return NotFound when a requested resource does not exist. The application may also configure status-code pages so unmatched routes and other 404 responses display a consistent user-facing page.
A missing business record should be distinguished from a server error. Returning an accurate 404 improves HTTP semantics, diagnostics, and search-engine behavior.
Code Example
public async Task<IActionResult> Details(int id)
{
var product = await _service.GetAsync(id);
if (product == null)
return NotFound();
return View(product);
}