-
Notifications
You must be signed in to change notification settings - Fork 25.3k
/
BlazorEndpointRouteBuilderExtensions.cs
93 lines (79 loc) · 2.66 KB
/
BlazorEndpointRouteBuilderExtensions.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Routing;
public static class BlazorEndpointRouteBuilderExtensions {
public static IEndpointConventionBuilder MapBlazorPages(
this IEndpointRouteBuilder endpoints, string page)
{
var assembly = Assembly.GetEntryAssembly();
if (assembly is null)
{
throw new InvalidOperationException("No entry assembly available.");
}
return endpoints.MapBlazorPages(page, assembly);
}
public static IEndpointConventionBuilder MapBlazorPages(
this IEndpointRouteBuilder endpoints, string page,
params Assembly[] assemblies)
{
ArgumentNullException.ThrowIfNull(assemblies);
var builder = new BlazorEndpointConventionBuilder();
foreach (var route in GetRoutes(assemblies))
{
var conventionBuilder = endpoints.MapFallbackToPage(route, page);
conventionBuilder.Add(b =>
{
b.DisplayName = $"Blazor {route}";
((RouteEndpointBuilder)b).Order = -1;
});
builder.Add(conventionBuilder);
}
return builder;
}
private static IEnumerable<string> GetRoutes(Assembly[] assemblies)
{
foreach (var assembly in assemblies)
{
foreach (var type in assembly.GetTypes())
{
if (typeof(IComponent).IsAssignableFrom(type))
{
foreach (var attribute in
type.GetCustomAttributes(typeof(RouteAttribute)))
{
if (attribute is RouteAttribute { Template: { } route })
{
yield return route;
}
}
}
}
}
}
private sealed class BlazorEndpointConventionBuilder : IEndpointConventionBuilder {
private readonly List<IEndpointConventionBuilder> builders = new();
public void Add(IEndpointConventionBuilder builder)
{
builders.Add(builder);
}
void IEndpointConventionBuilder.Add(Action<EndpointBuilder> convention)
{
foreach (var builder in builders)
{
builder.Add(convention);
}
}
#if NET7_0_OR_GREATER
void IEndpointConventionBuilder.Finally(
Action<EndpointBuilder> finalConvention)
{
foreach (var builder in builders)
{
builder.Finally(finalConvention);
}
}
#endif
}
}