Introduction
While building APIs in ASP.NET Core, handling errors correctly is as important as handling successful responses. Many applications return plain text error messages, which are difficult for client applications to understand and process.
ASP.NET Core addresses this problem using Problem Details, a standard and structured way of returning error information.
What Is Problem Details?
Problem Details is a standardized error response format defined by RFC 7807.It provides a consistent JSON structure for errors, including:
ASP.NET Core supports Problem Details out of the box.
Why Is Problem Details Important?
Consider this error response:
"User not found"
This response:
With Problem Details, error responses become clear, consistent, and easy to handle.
Simple 404 Example Using Built-in Support
For example, an API attempts to fetch a user by ID, but the user does not exist.
Controller Code :
[HttpGet("users/{id}")]
public IActionResult GetUser(int id)
{
return NotFound();
}
Response Returned by ASP.NET Core :
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
"title": "Not Found",
"status": 404
}
This approach requires no extra code, uses a standard error format, and is ideal for simple use cases
Complete 404 Example with Custom Problem Details:
Sometimes, we need to give more meaningful information to the client, such as which resource was not found.
Step 1: User Model
public class UserDto
{
public int Id { get; set; }
public string Email { get; set; }
}
Step 2: Users Controller
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private static readonly List<UserDto> Users = new()
{
new UserDto { Id = 1, Email = "[email protected]" }
};
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
var user = Users.FirstOrDefault(u => u.Id == id);
if (user == null)
{
return NotFound(new ProblemDetails
{
Title = "User not found",
Detail = $"User with id {id} does not exist",
Status = StatusCodes.Status404NotFound,
Type = "https://httpstatuses.com/404"
});
}
return Ok(user);
}
}
Step 3: API Request
GET /api/users/10
Step 4: 404 Problem Details Response
{
"type": "https://httpstatuses.com/404",
"title": "User not found",
"status": 404,
"detail": "User with id 10 does not exist"
}
This response clearly explains what went wrong, why it occurred, and which resource caused the issue.
Creating aProblemDetails object manually every time is unnecessary because ASP.NET Core automatically generates them for common errors, such as 404 (Not Found) and 400 (Bad Request). You should only create a custom ProblemDetails object when you need to provide additional clarity or specific metadata for an issue.
Conclusion
In this article we have seen, how Problem Details provides a clean, standard, and beginner-friendly way to handle errors in ASP.NET Core APIs.
Developers can rely on the framework’s default behavior and customize error responses only when needed.
Hope you enjoy reading this.