This repository has been archived by the owner on Nov 27, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 126
/
TreeRouter.cs
317 lines (272 loc) · 11.8 KB
/
TreeRouter.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Routing.Internal;
using Microsoft.AspNetCore.Routing.Logging;
using Microsoft.AspNetCore.Routing.Template;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
namespace Microsoft.AspNetCore.Routing.Tree
{
/// <summary>
/// An <see cref="IRouter"/> implementation for attribute routing.
/// </summary>
public class TreeRouter : IRouter
{
// Key used by routing and action selection to match an attribute route entry to a
// group of action descriptors.
public static readonly string RouteGroupKey = "!__route_group";
private readonly LinkGenerationDecisionTree _linkGenerationTree;
private readonly UrlMatchingTree[] _trees;
private readonly IDictionary<string, OutboundMatch> _namedEntries;
private readonly ILogger _logger;
private readonly ILogger _constraintLogger;
/// <summary>
/// Creates a new instance of <see cref="TreeRouter"/>.
/// </summary>
/// <param name="trees">The list of <see cref="UrlMatchingTree"/> that contains the route entries.</param>
/// <param name="linkGenerationEntries">The set of <see cref="OutboundRouteEntry"/>.</param>
/// <param name="urlEncoder">The <see cref="UrlEncoder"/>.</param>
/// <param name="objectPool">The <see cref="ObjectPool{T}"/>.</param>
/// <param name="routeLogger">The <see cref="ILogger"/> instance.</param>
/// <param name="constraintLogger">The <see cref="ILogger"/> instance used
/// in <see cref="RouteConstraintMatcher"/>.</param>
/// <param name="version">The version of this route.</param>
public TreeRouter(
UrlMatchingTree[] trees,
IEnumerable<OutboundRouteEntry> linkGenerationEntries,
UrlEncoder urlEncoder,
ObjectPool<UriBuildingContext> objectPool,
ILogger routeLogger,
ILogger constraintLogger,
int version)
{
if (trees == null)
{
throw new ArgumentNullException(nameof(trees));
}
if (linkGenerationEntries == null)
{
throw new ArgumentNullException(nameof(linkGenerationEntries));
}
if (urlEncoder == null)
{
throw new ArgumentNullException(nameof(urlEncoder));
}
if (objectPool == null)
{
throw new ArgumentNullException(nameof(objectPool));
}
if (routeLogger == null)
{
throw new ArgumentNullException(nameof(routeLogger));
}
if (constraintLogger == null)
{
throw new ArgumentNullException(nameof(constraintLogger));
}
_trees = trees;
_logger = routeLogger;
_constraintLogger = constraintLogger;
_namedEntries = new Dictionary<string, OutboundMatch>(StringComparer.OrdinalIgnoreCase);
var outboundMatches = new List<OutboundMatch>();
foreach (var entry in linkGenerationEntries)
{
var binder = new TemplateBinder(urlEncoder, objectPool, entry.RouteTemplate, entry.Defaults);
var outboundMatch = new OutboundMatch() { Entry = entry, TemplateBinder = binder };
outboundMatches.Add(outboundMatch);
// Skip unnamed entries
if (entry.RouteName == null)
{
continue;
}
// We only need to keep one OutboundMatch per route template
// so in case two entries have the same name and the same template we only keep
// the first entry.
if (_namedEntries.TryGetValue(entry.RouteName, out var namedMatch) &&
!string.Equals(
namedMatch.Entry.RouteTemplate.TemplateText,
entry.RouteTemplate.TemplateText,
StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(
Resources.FormatAttributeRoute_DifferentLinkGenerationEntries_SameName(entry.RouteName),
nameof(linkGenerationEntries));
}
else if (namedMatch == null)
{
_namedEntries.Add(entry.RouteName, outboundMatch);
}
}
// The decision tree will take care of ordering for these entries.
_linkGenerationTree = new LinkGenerationDecisionTree(outboundMatches.ToArray());
Version = version;
}
/// <summary>
/// Gets the version of this route.
/// </summary>
public int Version { get; }
internal IEnumerable<UrlMatchingTree> MatchingTrees => _trees;
/// <inheritdoc />
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// If it's a named route we will try to generate a link directly and
// if we can't, we will not try to generate it using an unnamed route.
if (context.RouteName != null)
{
return GetVirtualPathForNamedRoute(context);
}
// The decision tree will give us back all entries that match the provided route data in the correct
// order. We just need to iterate them and use the first one that can generate a link.
var matches = _linkGenerationTree.GetMatches(context.Values, context.AmbientValues);
if (matches == null)
{
return null;
}
for (var i = 0; i < matches.Count; i++)
{
var path = GenerateVirtualPath(context, matches[i].Match.Entry, matches[i].Match.TemplateBinder);
if (path != null)
{
return path;
}
}
return null;
}
/// <inheritdoc />
public async Task RouteAsync(RouteContext context)
{
foreach (var tree in _trees)
{
var tokenizer = new PathTokenizer(context.HttpContext.Request.Path);
var root = tree.Root;
var treeEnumerator = new TreeEnumerator(root, tokenizer);
// Create a snapshot before processing the route. We'll restore this snapshot before running each
// to restore the state. This is likely an "empty" snapshot, which doesn't allocate.
var snapshot = context.RouteData.PushState(router: null, values: null, dataTokens: null);
while (treeEnumerator.MoveNext())
{
var node = treeEnumerator.Current;
foreach (var item in node.Matches)
{
var entry = item.Entry;
var matcher = item.TemplateMatcher;
try
{
if (!matcher.TryMatch(context.HttpContext.Request.Path, context.RouteData.Values))
{
continue;
}
if (!RouteConstraintMatcher.Match(
entry.Constraints,
context.RouteData.Values,
context.HttpContext,
this,
RouteDirection.IncomingRequest,
_constraintLogger))
{
continue;
}
_logger.MatchedRoute(entry.RouteName, entry.RouteTemplate.TemplateText);
context.RouteData.Routers.Add(entry.Handler);
await entry.Handler.RouteAsync(context);
if (context.Handler != null)
{
return;
}
}
finally
{
if (context.Handler == null)
{
// Restore the original values to prevent polluting the route data.
snapshot.Restore();
}
}
}
}
}
}
private VirtualPathData GetVirtualPathForNamedRoute(VirtualPathContext context)
{
if (_namedEntries.TryGetValue(context.RouteName, out var match))
{
var path = GenerateVirtualPath(context, match.Entry, match.TemplateBinder);
if (path != null)
{
return path;
}
}
return null;
}
private VirtualPathData GenerateVirtualPath(
VirtualPathContext context,
OutboundRouteEntry entry,
TemplateBinder binder)
{
// In attribute the context includes the values that are used to select this entry - typically
// these will be the standard 'action', 'controller' and maybe 'area' tokens. However, we don't
// want to pass these to the link generation code, or else they will end up as query parameters.
//
// So, we need to exclude from here any values that are 'required link values', but aren't
// parameters in the template.
//
// Ex:
// template: api/Products/{action}
// required values: { id = "5", action = "Buy", Controller = "CoolProducts" }
//
// result: { id = "5", action = "Buy" }
var inputValues = new RouteValueDictionary();
foreach (var kvp in context.Values)
{
if (entry.RequiredLinkValues.ContainsKey(kvp.Key))
{
var parameter = entry.RouteTemplate.GetParameter(kvp.Key);
if (parameter == null)
{
continue;
}
}
inputValues.Add(kvp.Key, kvp.Value);
}
var bindingResult = binder.GetValues(context.AmbientValues, inputValues);
if (bindingResult == null)
{
// A required parameter in the template didn't get a value.
return null;
}
var matched = RouteConstraintMatcher.Match(
entry.Constraints,
bindingResult.CombinedValues,
context.HttpContext,
this,
RouteDirection.UrlGeneration,
_constraintLogger);
if (!matched)
{
// A constraint rejected this link.
return null;
}
var pathData = entry.Handler.GetVirtualPath(context);
if (pathData != null)
{
// If path is non-null then the target router short-circuited, we don't expect this
// in typical MVC scenarios.
return pathData;
}
var path = binder.BindValues(bindingResult.AcceptedValues);
if (path == null)
{
return null;
}
return new VirtualPathData(this, path);
}
}
}