- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathProgram.cs
51 lines (41 loc) · 1.21 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
usingSystem.ComponentModel.DataAnnotations;
usingMicrosoft.AspNetCore.Http.Validation;
varbuilder=WebApplication.CreateBuilder();
builder.Services.AddValidation();
varapp=builder.Build();
app.MapGet("/",()=>
{
varhtml="""
<html>
<body>
<h1>Validation on Route Parameters</h1>
<ul>
<li><a href="/validate/John/25">Valid Route</a></li>
<li><a href="/validate/Jonathan-Brand/51">Invalid Route</a></li>
</ul>
</body>
</html>
""";
returnTypedResults.Content(html,"text/html");
});//This is not an API endpoint
app.MapGet("/validate/{name}/{age}",([AsParameters]RouteInputinput)=>
{
returnTypedResults.Ok(input);
});
app.Run();
[ValidatableType]
publicclassRouteInput:IValidatableObject
{
[Required]
publicstringName{get;set;}=string.Empty;
[Required]
publicintAge{get;set;}=1;
publicIEnumerable<ValidationResult>Validate(ValidationContextvalidationContext)
{
if(Name.Length>10)
{
if(Age>50)
yieldreturnnewValidationResult("Age must be less than 50 when name is longer than 10 characters",[nameof(Name),nameof(Age)]);
}
}
}