I am porting an application from Asp.net Controllers to Asp.net Minimal-Apis. The current project is using model-based DataAnnotations. Controllers do model validation out of the box but MinApi does not.
For an example such as below, what is the best way to do DataAnnotation model validation in MinimalApi?
Example Data Annotation Model:
using System.ComponentModel.DataAnnotations;
namespace minApi.Models;
public class Account
{
[Required]
public int AccountId { get; set; }
[Required, MaxLength(50)]
public string AccountName { get; set; };
[Required, EmailAddress]
public string AccountEmail { get; set; };
[Required, Phone]
public string AccountPhone { get; set; };
[Required, MaxLength(50)]
public string StreetAddress { get; set; };
[Required, MaxLength(50)]
public string City { get; set; };
[Required, MaxLength(2)]
public string StateProvince { get; set; };
[Required, MaxLength(10)]
public string PostalCode { get; set; };
public bool IsActive { get; set; } = true;
public override string ToString() => $"{AccountName} AccountId: {AccountId}";
}
Example Minimal-Api With Model:
accounts.MapPost("/saveAccount", (IAccountManager _accountManager, [FromBody] Account account) =>
{
var acct = _accountManager.SaveAccount(account);
return Results.Ok(acct);
})