This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
DefaultApplicationModelProvider.cs
662 lines (570 loc) · 25.8 KB
/
DefaultApplicationModelProvider.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
// 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.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Mvc.Internal
{
public class DefaultApplicationModelProvider : IApplicationModelProvider
{
private readonly ICollection<IFilterMetadata> _globalFilters;
public DefaultApplicationModelProvider(IOptions<MvcOptions> mvcOptionsAccessor)
{
_globalFilters = mvcOptionsAccessor.Value.Filters;
}
/// <inheritdoc />
public int Order
{
get
{
return -1000;
}
}
/// <inheritdoc />
public virtual void OnProvidersExecuting(ApplicationModelProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
foreach (var filter in _globalFilters)
{
context.Result.Filters.Add(filter);
}
foreach (var controllerType in context.ControllerTypes)
{
var controllerModel = CreateControllerModel(controllerType);
if (controllerModel == null)
{
continue;
}
context.Result.Controllers.Add(controllerModel);
controllerModel.Application = context.Result;
foreach (var propertyHelper in PropertyHelper.GetProperties(controllerType.AsType()))
{
var propertyInfo = propertyHelper.Property;
var propertyModel = CreatePropertyModel(propertyInfo);
if (propertyModel != null)
{
propertyModel.Controller = controllerModel;
controllerModel.ControllerProperties.Add(propertyModel);
}
}
foreach (var methodInfo in controllerType.AsType().GetMethods())
{
var actionModel = CreateActionModel(controllerType, methodInfo);
if (actionModel == null)
{
continue;
}
actionModel.Controller = controllerModel;
controllerModel.Actions.Add(actionModel);
foreach (var parameterInfo in actionModel.ActionMethod.GetParameters())
{
var parameterModel = CreateParameterModel(parameterInfo);
if (parameterModel != null)
{
parameterModel.Action = actionModel;
actionModel.Parameters.Add(parameterModel);
}
}
}
}
}
/// <inheritdoc />
public virtual void OnProvidersExecuted(ApplicationModelProviderContext context)
{
// Intentionally empty.
}
/// <summary>
/// Creates a <see cref="ControllerModel"/> for the given <see cref="TypeInfo"/>.
/// </summary>
/// <param name="typeInfo">The <see cref="TypeInfo"/>.</param>
/// <returns>A <see cref="ControllerModel"/> for the given <see cref="TypeInfo"/>.</returns>
protected virtual ControllerModel CreateControllerModel(TypeInfo typeInfo)
{
if (typeInfo == null)
{
throw new ArgumentNullException(nameof(typeInfo));
}
// For attribute routes on a controller, we want want to support 'overriding' routes on a derived
// class. So we need to walk up the hierarchy looking for the first class to define routes.
//
// Then we want to 'filter' the set of attributes, so that only the effective routes apply.
var currentTypeInfo = typeInfo;
var objectTypeInfo = typeof(object).GetTypeInfo();
IRouteTemplateProvider[] routeAttributes = null;
do
{
routeAttributes = currentTypeInfo
.GetCustomAttributes(inherit: false)
.OfType<IRouteTemplateProvider>()
.ToArray();
if (routeAttributes.Length > 0)
{
// Found 1 or more route attributes.
break;
}
currentTypeInfo = currentTypeInfo.BaseType.GetTypeInfo();
}
while (currentTypeInfo != objectTypeInfo);
// CoreCLR returns IEnumerable<Attribute> from GetCustomAttributes - the OfType<object>
// is needed to so that the result of ToArray() is object
var attributes = typeInfo.GetCustomAttributes(inherit: true).OfType<object>().ToArray();
// This is fairly complicated so that we maintain referential equality between items in
// ControllerModel.Attributes and ControllerModel.Attributes[*].Attribute.
var filteredAttributes = new List<object>();
foreach (var attribute in attributes)
{
if (attribute is IRouteTemplateProvider)
{
// This attribute is a route-attribute, leave it out.
}
else
{
filteredAttributes.Add(attribute);
}
}
filteredAttributes.AddRange(routeAttributes);
attributes = filteredAttributes.ToArray();
var controllerModel = new ControllerModel(typeInfo, attributes);
AddRange(controllerModel.Selectors, CreateSelectors(attributes));
controllerModel.ControllerName =
typeInfo.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) ?
typeInfo.Name.Substring(0, typeInfo.Name.Length - "Controller".Length) :
typeInfo.Name;
AddRange(controllerModel.Filters, attributes.OfType<IFilterMetadata>());
foreach (var routeValueProvider in attributes.OfType<IRouteValueProvider>())
{
controllerModel.RouteValues.Add(routeValueProvider.RouteKey, routeValueProvider.RouteValue);
}
var apiVisibility = attributes.OfType<IApiDescriptionVisibilityProvider>().FirstOrDefault();
if (apiVisibility != null)
{
controllerModel.ApiExplorer.IsVisible = !apiVisibility.IgnoreApi;
}
var apiGroupName = attributes.OfType<IApiDescriptionGroupNameProvider>().FirstOrDefault();
if (apiGroupName != null)
{
controllerModel.ApiExplorer.GroupName = apiGroupName.GroupName;
}
// Controllers can implement action filter and result filter interfaces. We add
// a special delegating filter implementation to the pipeline to handle it.
//
// This is needed because filters are instantiated before the controller.
if (typeof(IAsyncActionFilter).GetTypeInfo().IsAssignableFrom(typeInfo) ||
typeof(IActionFilter).GetTypeInfo().IsAssignableFrom(typeInfo))
{
controllerModel.Filters.Add(new ControllerActionFilter());
}
if (typeof(IAsyncResultFilter).GetTypeInfo().IsAssignableFrom(typeInfo) ||
typeof(IResultFilter).GetTypeInfo().IsAssignableFrom(typeInfo))
{
controllerModel.Filters.Add(new ControllerResultFilter());
}
return controllerModel;
}
/// <summary>
/// Creates a <see cref="PropertyModel"/> for the given <see cref="PropertyInfo"/>.
/// </summary>
/// <param name="propertyInfo">The <see cref="PropertyInfo"/>.</param>
/// <returns>A <see cref="PropertyModel"/> for the given <see cref="PropertyInfo"/>.</returns>
protected virtual PropertyModel CreatePropertyModel(PropertyInfo propertyInfo)
{
if (propertyInfo == null)
{
throw new ArgumentNullException(nameof(propertyInfo));
}
// CoreCLR returns IEnumerable<Attribute> from GetCustomAttributes - the OfType<object>
// is needed to so that the result of ToArray() is object
var attributes = propertyInfo.GetCustomAttributes(inherit: true).OfType<object>().ToArray();
var propertyModel = new PropertyModel(propertyInfo, attributes);
var bindingInfo = BindingInfo.GetBindingInfo(attributes);
propertyModel.BindingInfo = bindingInfo;
propertyModel.PropertyName = propertyInfo.Name;
return propertyModel;
}
/// <summary>
/// Creates the <see cref="ActionModel"/> instance for the given action <see cref="MethodInfo"/>.
/// </summary>
/// <param name="typeInfo">The controller <see cref="TypeInfo"/>.</param>
/// <param name="methodInfo">The action <see cref="MethodInfo"/>.</param>
/// <returns>
/// An <see cref="ActionModel"/> instance for the given action <see cref="MethodInfo"/> or
/// <c>null</c> if the <paramref name="methodInfo"/> does not represent an action.
/// </returns>
protected virtual ActionModel CreateActionModel(
TypeInfo typeInfo,
MethodInfo methodInfo)
{
if (typeInfo == null)
{
throw new ArgumentNullException(nameof(typeInfo));
}
if (methodInfo == null)
{
throw new ArgumentNullException(nameof(methodInfo));
}
if (!IsAction(typeInfo, methodInfo))
{
return null;
}
// CoreCLR returns IEnumerable<Attribute> from GetCustomAttributes - the OfType<object>
// is needed to so that the result of ToArray() is object
var attributes = methodInfo.GetCustomAttributes(inherit: true).OfType<object>().ToArray();
var actionModel = new ActionModel(methodInfo, attributes);
AddRange(actionModel.Filters, attributes.OfType<IFilterMetadata>());
var actionName = attributes.OfType<ActionNameAttribute>().FirstOrDefault();
if (actionName?.Name != null)
{
actionModel.ActionName = actionName.Name;
}
else
{
actionModel.ActionName = methodInfo.Name;
}
var apiVisibility = attributes.OfType<IApiDescriptionVisibilityProvider>().FirstOrDefault();
if (apiVisibility != null)
{
actionModel.ApiExplorer.IsVisible = !apiVisibility.IgnoreApi;
}
var apiGroupName = attributes.OfType<IApiDescriptionGroupNameProvider>().FirstOrDefault();
if (apiGroupName != null)
{
actionModel.ApiExplorer.GroupName = apiGroupName.GroupName;
}
foreach (var routeValueProvider in attributes.OfType<IRouteValueProvider>())
{
actionModel.RouteValues.Add(routeValueProvider.RouteKey, routeValueProvider.RouteValue);
}
//TODO: modify comment
// Now we need to determine the action selection info (cross-section of routes and constraints)
//
// For attribute routes on a action, we want want to support 'overriding' routes on a
// virtual method, but allow 'overriding'. So we need to walk up the hierarchy looking
// for the first definition to define routes.
//
// Then we want to 'filter' the set of attributes, so that only the effective routes apply.
var currentMethodInfo = methodInfo;
IRouteTemplateProvider[] routeAttributes = null;
while (true)
{
routeAttributes = currentMethodInfo
.GetCustomAttributes(inherit: false)
.OfType<IRouteTemplateProvider>()
.ToArray();
if (routeAttributes.Length > 0)
{
// Found 1 or more route attributes.
break;
}
// GetBaseDefinition returns 'this' when it gets to the bottom of the chain.
var nextMethodInfo = currentMethodInfo.GetBaseDefinition();
if (currentMethodInfo == nextMethodInfo)
{
break;
}
currentMethodInfo = nextMethodInfo;
}
// This is fairly complicated so that we maintain referential equality between items in
// ActionModel.Attributes and ActionModel.Attributes[*].Attribute.
var applicableAttributes = new List<object>();
foreach (var attribute in attributes)
{
if (attribute is IRouteTemplateProvider)
{
// This attribute is a route-attribute, leave it out.
}
else
{
applicableAttributes.Add(attribute);
}
}
applicableAttributes.AddRange(routeAttributes);
AddRange(actionModel.Selectors, CreateSelectors(applicableAttributes));
return actionModel;
}
/// <summary>
/// Returns <c>true</c> if the <paramref name="methodInfo"/> is an action. Otherwise <c>false</c>.
/// </summary>
/// <param name="typeInfo">The <see cref="TypeInfo"/>.</param>
/// <param name="methodInfo">The <see cref="MethodInfo"/>.</param>
/// <returns><c>true</c> if the <paramref name="methodInfo"/> is an action. Otherwise <c>false</c>.</returns>
/// <remarks>
/// Override this method to provide custom logic to determine which methods are considered actions.
/// </remarks>
protected virtual bool IsAction(TypeInfo typeInfo, MethodInfo methodInfo)
{
if (typeInfo == null)
{
throw new ArgumentNullException(nameof(typeInfo));
}
if (methodInfo == null)
{
throw new ArgumentNullException(nameof(methodInfo));
}
// The SpecialName bit is set to flag members that are treated in a special way by some compilers
// (such as property accessors and operator overloading methods).
if (methodInfo.IsSpecialName)
{
return false;
}
if (methodInfo.IsDefined(typeof(NonActionAttribute)))
{
return false;
}
// Overriden methods from Object class, e.g. Equals(Object), GetHashCode(), etc., are not valid.
if (methodInfo.GetBaseDefinition().DeclaringType == typeof(object))
{
return false;
}
// Dispose method implemented from IDisposable is not valid
if (IsIDisposableMethod(methodInfo))
{
return false;
}
if (methodInfo.IsStatic)
{
return false;
}
if (methodInfo.IsAbstract)
{
return false;
}
if (methodInfo.IsConstructor)
{
return false;
}
if (methodInfo.IsGenericMethod)
{
return false;
}
return methodInfo.IsPublic;
}
/// <summary>
/// Creates a <see cref="ParameterModel"/> for the given <see cref="ParameterInfo"/>.
/// </summary>
/// <param name="parameterInfo">The <see cref="ParameterInfo"/>.</param>
/// <returns>A <see cref="ParameterModel"/> for the given <see cref="ParameterInfo"/>.</returns>
protected virtual ParameterModel CreateParameterModel(ParameterInfo parameterInfo)
{
if (parameterInfo == null)
{
throw new ArgumentNullException(nameof(parameterInfo));
}
// CoreCLR returns IEnumerable<Attribute> from GetCustomAttributes - the OfType<object>
// is needed to so that the result of ToArray() is object
var attributes = parameterInfo.GetCustomAttributes(inherit: true).OfType<object>().ToArray();
var parameterModel = new ParameterModel(parameterInfo, attributes);
var bindingInfo = BindingInfo.GetBindingInfo(attributes);
parameterModel.BindingInfo = bindingInfo;
parameterModel.ParameterName = parameterInfo.Name;
return parameterModel;
}
private IList<SelectorModel> CreateSelectors(IList<object> attributes)
{
// Route attributes create multiple selector models, we want to split the set of
// attributes based on these so each selector only has the attributes that affect it.
//
// The set of route attributes are split into those that 'define' a route versus those that are
// 'silent'.
//
// We need to define a selector for each attribute that 'defines' a route, and a single selector
// for all of the ones that don't (if any exist).
//
// If the attribute that 'defines' a route is NOT an IActionHttpMethodProvider, then we'll include with
// it, any IActionHttpMethodProvider that are 'silent' IRouteTemplateProviders. In this case the 'extra'
// action for silent route providers isn't needed.
//
// Ex:
// [HttpGet]
// [AcceptVerbs("POST", "PUT")]
// [HttpPost("Api/Things")]
// public void DoThing()
//
// This will generate 2 selectors:
// 1. [HttpPost("Api/Things")]
// 2. [HttpGet], [AcceptVerbs("POST", "PUT")]
//
// Another example of this situation is:
//
// [Route("api/Products")]
// [AcceptVerbs("GET", "HEAD")]
// [HttpPost("api/Products/new")]
//
// This will generate 2 selectors:
// 1. [AcceptVerbs("GET", "HEAD")]
// 2. [HttpPost]
//
// Note that having a route attribute that doesn't define a route template _might_ be an error. We
// don't have enough context to really know at this point so we just pass it on.
var routeProviders = new List<IRouteTemplateProvider>();
var createSelectorForSilentRouteProviders = false;
foreach (var attribute in attributes)
{
var routeTemplateProvider = attribute as IRouteTemplateProvider;
if (routeTemplateProvider != null)
{
if (IsSilentRouteAttribute(routeTemplateProvider))
{
createSelectorForSilentRouteProviders = true;
}
else
{
routeProviders.Add(routeTemplateProvider);
}
}
}
foreach (var routeProvider in routeProviders)
{
// If we see an attribute like
// [Route(...)]
//
// Then we want to group any attributes like [HttpGet] with it.
//
// Basically...
//
// [HttpGet]
// [HttpPost("Products")]
// public void Foo() { }
//
// Is two selectors. And...
//
// [HttpGet]
// [Route("Products")]
// public void Foo() { }
//
// Is one selector.
if (!(routeProvider is IActionHttpMethodProvider))
{
createSelectorForSilentRouteProviders = false;
}
}
var selectorModels = new List<SelectorModel>();
if (routeProviders.Count == 0 && !createSelectorForSilentRouteProviders)
{
// Simple case, all attributes apply
selectorModels.Add(CreateSelectorModel(route: null, attributes: attributes));
}
else
{
// Each of these routeProviders are the ones that actually have routing information on them
// something like [HttpGet] won't show up here, but [HttpGet("Products")] will.
foreach (var routeProvider in routeProviders)
{
var filteredAttributes = new List<object>();
foreach (var attribute in attributes)
{
if (ReferenceEquals(attribute, routeProvider))
{
filteredAttributes.Add(attribute);
}
else if (InRouteProviders(routeProviders, attribute))
{
// Exclude other route template providers
// Example:
// [HttpGet("template")]
// [Route("template/{id}")]
}
else if (
routeProvider is IActionHttpMethodProvider &&
attribute is IActionHttpMethodProvider)
{
// Example:
// [HttpGet("template")]
// [AcceptVerbs("GET", "POST")]
//
// Exclude other http method providers if this route is an
// http method provider.
}
else
{
filteredAttributes.Add(attribute);
}
}
selectorModels.Add(CreateSelectorModel(routeProvider, filteredAttributes));
}
if (createSelectorForSilentRouteProviders)
{
var filteredAttributes = new List<object>();
foreach (var attribute in attributes)
{
if (!InRouteProviders(routeProviders, attribute))
{
filteredAttributes.Add(attribute);
}
}
selectorModels.Add(CreateSelectorModel(route: null, attributes: filteredAttributes));
}
}
return selectorModels;
}
private static bool InRouteProviders(List<IRouteTemplateProvider> routeProviders, object attribute)
{
foreach (var rp in routeProviders)
{
if (ReferenceEquals(rp, attribute))
{
return true;
}
}
return false;
}
private static SelectorModel CreateSelectorModel(IRouteTemplateProvider route, IList<object> attributes)
{
var selectorModel = new SelectorModel();
if (route != null)
{
selectorModel.AttributeRouteModel = new AttributeRouteModel(route);
}
AddRange(selectorModel.ActionConstraints, attributes.OfType<IActionConstraintMetadata>());
// Simple case, all HTTP method attributes apply
var httpMethods = attributes
.OfType<IActionHttpMethodProvider>()
.SelectMany(a => a.HttpMethods)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
if (httpMethods.Length > 0)
{
selectorModel.ActionConstraints.Add(new HttpMethodActionConstraint(httpMethods));
}
return selectorModel;
}
private bool IsIDisposableMethod(MethodInfo methodInfo)
{
// Ideally we do not want Dispose method to be exposed as an action. However there are some scenarios where a user
// might want to expose a method with name "Dispose" (even though they might not be really disposing resources)
// Example: A controller deriving from MVC's Controller type might wish to have a method with name Dispose,
// in which case they can use the "new" keyword to hide the base controller's declaration.
// Find where the method was originally declared
var baseMethodInfo = methodInfo.GetBaseDefinition();
var declaringTypeInfo = baseMethodInfo.DeclaringType.GetTypeInfo();
return
(typeof(IDisposable).GetTypeInfo().IsAssignableFrom(declaringTypeInfo) &&
declaringTypeInfo.GetRuntimeInterfaceMap(typeof(IDisposable)).TargetMethods[0] == baseMethodInfo);
}
private bool IsSilentRouteAttribute(IRouteTemplateProvider routeTemplateProvider)
{
return
routeTemplateProvider.Template == null &&
routeTemplateProvider.Order == null &&
routeTemplateProvider.Name == null;
}
private static void AddRange<T>(IList<T> list, IEnumerable<T> items)
{
foreach (var item in items)
{
list.Add(item);
}
}
}
}