ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

ASP.NET Core Tutorial• 7 min read

Model Validation & RFC 7807 ProblemDetails

Enforcing data integrity with DataAnnotations and standardizing API error responses

Data integrity is the frontline defense of any backend service. ASP.NET Core provides DataAnnotations attributes that automatically validate incoming models and return standardized RFC 7807 ProblemDetails JSON error envelopes.

DataAnnotations and ProblemDetails Responses

[Required]: Ensures the property is not null or empty.

[StringLength(100, MinimumLength = 3)]: Enforces string boundary constraints.

[Range(0.01, 1000.00)]: Validates numeric ranges.

[EmailAddress]: Enforces valid email syntax.

RFC 7807 ProblemDetails: Standardizes HTTP error responses across the industry with type, title, status, and errors fields.

Validated DTO Model with DataAnnotations
using System.ComponentModel.DataAnnotations;

public class CreateCourseRequest
{
    [Required(ErrorMessage = "Course title is mandatory.")]
    [StringLength(150, MinimumLength = 5, ErrorMessage = "Title must be between 5 and 150 characters.")]
    public string Title { get; set; } = string.Empty;

    [Required]
    [Range(0.0, 999.99, ErrorMessage = "Price must be between $0.00 and $999.99")]
    public decimal Price { get; set; }

    [Required]
    [EmailAddress(ErrorMessage = "Please supply a valid instructor contact email.")]
    public string InstructorEmail { get; set; } = string.Empty;
}
When invalid payloads hit an [ApiController], ASP.NET Core automatically responds with HTTP 400 Bad Request.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which RFC standard defines the machine-readable error format ProblemDetails implemented by ASP.NET Core?