DamianEdwards / MinimalApis.Extensions

A set of extensions and helpers for working with ASP.NET Core Minimal APIs.
MIT License
298 stars 27 forks source link

Support interface-based validated parameter binding #13

Open DamianEdwards opened 3 years ago

DamianEdwards commented 3 years ago

Thanks to recent changes in rc.2 (dotnet/aspnetcore#36935), something like the following should now be possible:

app.MapPost("/todos", (Todo todo, TodoDb db) =>
{
    if (!todo.IsValid(out var errors))
    {
        return Result.ValidationProblem(errors);
    }
    db.Todos.Add(todo);
    await db.SaveChanges();
    return Result.Created($"/todos/{todo.Id}", todo);
});

public class Todo : IValidatable<Todo>
{
    [Required]
    public string? Title { get; set; }
}

namespace MiniValidation
{
    public interface IValidatable<TValue> where TValue : IValidatable<TValue>
    {
        public sealed IsValid(out IDictionary<string, string[]> errors)
        {
            var isValid = MiniValidator.TryValidate(this, out var errs);
            errors = errs;
            return isValid;
        }
    }
}