Some validation rules need more than a quick format check. For example, a student ID may look valid but already exist in a database. ASP.NET Core 11 lets a Minimal API run an asynchronous validation rule before its endpoint handler. This lesson shows the flow with a tiny in-memory checker, then explains where a real database call belongs.
POST JSON → Required fields → Async ID check → Endpoint if valid
Set up a .NET 11 Minimal API
Install the .NET 11 SDK. Make a new project with dotnet new web -n StudentValidation -f net11.0, then enter its folder. The example below is for .NET 11 Minimal APIs. ASP.NET Core MVC and Razor Pages use a different validation pipeline; do not assume this example automatically runs there.
Replace Program.cs
AddValidation() enables validation before the endpoint handler. [Required] handles missing values. The custom AsyncValidationAttribute asks a registered service whether the student ID already exists.
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidation();
builder.Services.AddSingleton<IStudentIds, DemoStudentIds>();
var app = builder.Build();
app.MapPost("/check-student", (StudentRequest request) =>
Results.Ok(new { message = "Student ID is available", request.StudentId }));
app.Run();
public sealed class StudentRequest
{
[Required]
public string Name { get; set; } = "";
[Required]
[AvailableStudentId]
public string StudentId { get; set; } = "";
}
public sealed class AvailableStudentIdAttribute : AsyncValidationAttribute
{
protected override ValidationResult? IsValid(object? value, ValidationContext context) =>
throw new InvalidOperationException("Use asynchronous validation for this rule.");
protected override async Task<ValidationResult?> IsValidAsync(
object? value, ValidationContext context, CancellationToken cancellationToken)
{
if (value is not string id || string.IsNullOrWhiteSpace(id))
return ValidationResult.Success; // [Required] handles empty input.
var ids = context.GetRequiredService<IStudentIds>();
if (await ids.ExistsAsync(id, cancellationToken))
return new ValidationResult("That student ID is already used.");
return ValidationResult.Success;
}
}
public interface IStudentIds
{
Task<bool> ExistsAsync(string id, CancellationToken cancellationToken);
}
public sealed class DemoStudentIds : IStudentIds
{
public Task<bool> ExistsAsync(string id, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(id.Equals("S100", StringComparison.OrdinalIgnoreCase));
}
}
The demo service treats S100 as already used. Its Task.FromResult is only a stand-in: it does not read a database and does not provide a real asynchronous I/O benefit. In an application, replace DemoStudentIds with a repository that awaits a database query and accepts the cancellation token.
Try two requests
Start the app with dotnet run --urls http://localhost:5055. Send a JSON POST to http://localhost:5055/check-student with {"name":"Asha","studentId":"S200"}. The endpoint should return a successful response saying the ID is available. Change the ID to S100; validation should reject the request before the endpoint runs. An empty name should also fail the required-field check.
What to remember
- Use ordinary synchronous rules for cheap checks such as required fields and string length.
- Use asynchronous rules when validation genuinely awaits I/O, such as a database or remote service.
- The synchronous
IsValidmethod throws here because this attribute is designed to run only through the async validation pipeline. - A uniqueness check is not enough to guarantee uniqueness under concurrent requests. Enforce a unique constraint in the database too.
Practice
- Make
S101another used ID in the demo service and predict the response. - Add a
[StringLength]rule to the name and try a long value. - Explain why a database unique constraint is still needed.
Continue with the ASP.NET Core student learning path. See Microsoft's ASP.NET Core 11 release notes and validation guide for full API details.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.