-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
RouteCollection.cs
198 lines (163 loc) · 5.77 KB
/
RouteCollection.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Routing;
/// <summary>
/// Supports managing a collection for multiple routes.
/// </summary>
public class RouteCollection : IRouteCollection
{
private readonly List<IRouter> _routes = new List<IRouter>();
private readonly List<IRouter> _unnamedRoutes = new List<IRouter>();
private readonly Dictionary<string, INamedRouter> _namedRoutes =
new Dictionary<string, INamedRouter>(StringComparer.OrdinalIgnoreCase);
private RouteOptions? _options;
/// <summary>
/// Gets the route at a given index.
/// </summary>
/// <value>The route at the given index.</value>
public IRouter this[int index]
{
get { return _routes[index]; }
}
/// <summary>
/// Gets the total number of routes registered in the collection.
/// </summary>
public int Count
{
get { return _routes.Count; }
}
/// <inheritdoc />
public void Add(IRouter router)
{
ArgumentNullException.ThrowIfNull(router);
var namedRouter = router as INamedRouter;
if (namedRouter != null)
{
if (!string.IsNullOrEmpty(namedRouter.Name))
{
_namedRoutes.Add(namedRouter.Name, namedRouter);
}
}
else
{
_unnamedRoutes.Add(router);
}
_routes.Add(router);
}
/// <inheritdoc />
public virtual async Task RouteAsync(RouteContext context)
{
// Perf: We want to avoid allocating a new RouteData for each route we need to process.
// We can do this by snapshotting the state at the beginning and then restoring it
// for each router we execute.
var snapshot = context.RouteData.PushState(null, values: null, dataTokens: null);
for (var i = 0; i < Count; i++)
{
var route = this[i];
context.RouteData.Routers.Add(route);
try
{
await route.RouteAsync(context);
if (context.Handler != null)
{
break;
}
}
finally
{
if (context.Handler == null)
{
snapshot.Restore();
}
}
}
}
/// <inheritdoc />
public virtual VirtualPathData? GetVirtualPath(VirtualPathContext context)
{
EnsureOptions(context.HttpContext);
if (!string.IsNullOrEmpty(context.RouteName))
{
VirtualPathData? namedRoutePathData = null;
if (_namedRoutes.TryGetValue(context.RouteName, out var matchedNamedRoute))
{
namedRoutePathData = matchedNamedRoute.GetVirtualPath(context);
}
var pathData = GetVirtualPath(context, _unnamedRoutes);
// If the named route and one of the unnamed routes also matches, then we have an ambiguity.
if (namedRoutePathData != null && pathData != null)
{
var message = Resources.FormatNamedRoutes_AmbiguousRoutesFound(context.RouteName);
throw new InvalidOperationException(message);
}
return NormalizeVirtualPath(namedRoutePathData ?? pathData);
}
else
{
return NormalizeVirtualPath(GetVirtualPath(context, _routes));
}
}
private static VirtualPathData? GetVirtualPath(VirtualPathContext context, List<IRouter> routes)
{
for (var i = 0; i < routes.Count; i++)
{
var route = routes[i];
var pathData = route.GetVirtualPath(context);
if (pathData != null)
{
return pathData;
}
}
return null;
}
private VirtualPathData? NormalizeVirtualPath(VirtualPathData? pathData)
{
if (pathData == null)
{
return pathData;
}
Debug.Assert(_options != null);
var url = pathData.VirtualPath;
if (!string.IsNullOrEmpty(url) && (_options.LowercaseUrls || _options.AppendTrailingSlash))
{
var indexOfSeparator = url.AsSpan().IndexOfAny('?', '#');
var urlWithoutQueryString = url;
var queryString = string.Empty;
if (indexOfSeparator != -1)
{
urlWithoutQueryString = url.Substring(0, indexOfSeparator);
queryString = url.Substring(indexOfSeparator);
}
if (_options.LowercaseUrls)
{
urlWithoutQueryString = urlWithoutQueryString.ToLowerInvariant();
}
if (_options.LowercaseUrls && _options.LowercaseQueryStrings)
{
queryString = queryString.ToLowerInvariant();
}
if (_options.AppendTrailingSlash && !urlWithoutQueryString.EndsWith('/'))
{
urlWithoutQueryString += "/";
}
// queryString will contain the delimiter ? or # as the first character, so it's safe to append.
url = urlWithoutQueryString + queryString;
return new VirtualPathData(pathData.Router, url, pathData.DataTokens);
}
return pathData;
}
[MemberNotNull(nameof(_options))]
private void EnsureOptions(HttpContext context)
{
if (_options == null)
{
_options = context.RequestServices.GetRequiredService<IOptions<RouteOptions>>().Value;
}
}
}