Skip to content

Instantly share code, notes, and snippets.

@stormwild
Forked from dj-nitehawk/Program.cs
Created October 1, 2024 09:03
Show Gist options
  • Save stormwild/0df9cf76cc45ceb30d2c8bf776288f19 to your computer and use it in GitHub Desktop.
Save stormwild/0df9cf76cc45ceb30d2c8bf776288f19 to your computer and use it in GitHub Desktop.
Request DTO inheritance with Validator composition
public class BaseRequest
{
public string? Id { get; init; }
}
public class BaseRequestValidator : Validator<BaseRequest>
{
public BaseRequestValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage("id is required!")
.Must(x => Guid.TryParse(x, out _)).WithMessage("must be a valid guid!");
}
}
public class Request : BaseRequest
{
public string? Title { get; set; }
}
public class RequestValidator : Validator<Request>
{
public RequestValidator()
{
Include(new BaseRequestValidator()); //include the validator for the base dto
RuleFor(x => x.Title).NotEmpty().WithMessage("title is required!");
}
}
public class Endpoint : Endpoint<Request>
{
public override void Configure()
{
Post("test");
AllowAnonymous();
}
public override async Task HandleAsync(Request r, CancellationToken c)
{
await SendAsync(r);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment