This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
/
CollectionModelBinder.cs
476 lines (413 loc) · 19.3 KB
/
CollectionModelBinder.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
// 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.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
{
/// <summary>
/// <see cref="IModelBinder"/> implementation for binding collection values.
/// </summary>
/// <typeparam name="TElement">Type of elements in the collection.</typeparam>
public class CollectionModelBinder<TElement> : ICollectionModelBinder
{
private static readonly IValueProvider EmptyValueProvider = new CompositeValueProvider();
private Func<object> _modelCreator;
/// <summary>
/// <para>This constructor is obsolete and will be removed in a future version. The recommended alternative
/// is the overload that also takes an <see cref="ILoggerFactory"/>.</para>
/// <para>Creates a new <see cref="CollectionModelBinder{TElement}"/>.</para>
/// </summary>
/// <param name="elementBinder">The <see cref="IModelBinder"/> for binding elements.</param>
[Obsolete("This constructor is obsolete and will be removed in a future version. The recommended alternative"
+ " is the overload that also takes an " + nameof(ILoggerFactory) + ".")]
public CollectionModelBinder(IModelBinder elementBinder)
: this(elementBinder, NullLoggerFactory.Instance)
{
}
/// <summary>
/// Creates a new <see cref="CollectionModelBinder{TElement}"/>.
/// </summary>
/// <param name="elementBinder">The <see cref="IModelBinder"/> for binding elements.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
/// <remarks>
/// The binder will not add an error for an unbound top-level model even if
/// <see cref="ModelMetadata.IsBindingRequired"/> is <see langword="true"/>.
/// </remarks>
public CollectionModelBinder(IModelBinder elementBinder, ILoggerFactory loggerFactory)
: this(elementBinder, loggerFactory, allowValidatingTopLevelNodes: false)
{
}
/// <summary>
/// Creates a new <see cref="CollectionModelBinder{TElement}"/>.
/// </summary>
/// <param name="elementBinder">The <see cref="IModelBinder"/> for binding elements.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
/// <param name="allowValidatingTopLevelNodes">
/// Indication that validation of top-level models is enabled. If <see langword="true"/> and
/// <see cref="ModelMetadata.IsBindingRequired"/> is <see langword="true"/> for a top-level model, the binder
/// adds a <see cref="ModelStateDictionary"/> error when the model is not bound.
/// </param>
public CollectionModelBinder(
IModelBinder elementBinder,
ILoggerFactory loggerFactory,
bool allowValidatingTopLevelNodes)
{
if (elementBinder == null)
{
throw new ArgumentNullException(nameof(elementBinder));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
ElementBinder = elementBinder;
Logger = loggerFactory.CreateLogger(GetType());
AllowValidatingTopLevelNodes = allowValidatingTopLevelNodes;
}
// Internal for testing.
internal bool AllowValidatingTopLevelNodes { get; }
/// <summary>
/// Gets the <see cref="IModelBinder"/> instances for binding collection elements.
/// </summary>
protected IModelBinder ElementBinder { get; }
/// <summary>
/// The <see cref="ILogger"/> used for logging in this binder.
/// </summary>
protected ILogger Logger { get; }
/// <inheritdoc />
public virtual async Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
Logger.AttemptingToBindModel(bindingContext);
var model = bindingContext.Model;
if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
{
Logger.FoundNoValueInRequest(bindingContext);
// If we failed to find data for a top-level model, then generate a
// default 'empty' model (or use existing Model) and return it.
if (bindingContext.IsTopLevelObject)
{
if (model == null)
{
model = CreateEmptyCollection(bindingContext.ModelType);
}
if (AllowValidatingTopLevelNodes)
{
AddErrorIfBindingRequired(bindingContext);
}
bindingContext.Result = ModelBindingResult.Success(model);
}
Logger.DoneAttemptingToBindModel(bindingContext);
return;
}
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
CollectionResult result;
if (valueProviderResult == ValueProviderResult.None)
{
Logger.NoNonIndexBasedFormatFoundForCollection(bindingContext);
result = await BindComplexCollection(bindingContext);
}
else
{
result = await BindSimpleCollection(bindingContext, valueProviderResult);
}
var boundCollection = result.Model;
if (model == null)
{
model = ConvertToCollectionType(bindingContext.ModelType, boundCollection);
}
else
{
// Special case for TryUpdateModelAsync(collection, ...) scenarios. Model is null in all other cases.
CopyToModel(model, boundCollection);
}
Debug.Assert(model != null);
if (result.ValidationStrategy != null)
{
bindingContext.ValidationState.Add(model, new ValidationStateEntry()
{
Strategy = result.ValidationStrategy,
});
}
if (valueProviderResult != ValueProviderResult.None)
{
// If we did simple binding, then modelstate should be updated to reflect what we bound for ModelName.
// If we did complex binding, there will already be an entry for each index.
bindingContext.ModelState.SetModelValue(
bindingContext.ModelName,
valueProviderResult);
}
bindingContext.Result = ModelBindingResult.Success(model);
Logger.DoneAttemptingToBindModel(bindingContext);
}
/// <inheritdoc />
public virtual bool CanCreateInstance(Type targetType)
{
if (targetType.IsAssignableFrom(typeof(List<TElement>)))
{
// Simple case such as ICollection<TElement>, IEnumerable<TElement> and IList<TElement>.
return true;
}
return targetType.GetTypeInfo().IsClass &&
!targetType.GetTypeInfo().IsAbstract &&
typeof(ICollection<TElement>).IsAssignableFrom(targetType);
}
/// <summary>
/// Add a <see cref="ModelError" /> to <see cref="ModelBindingContext.ModelState" /> if
/// <see cref="ModelMetadata.IsBindingRequired" />.
/// </summary>
/// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param>
/// <remarks>
/// <para>
/// This method should be called only when <see cref="MvcOptions.AllowValidatingTopLevelNodes" /> is
/// <see langword="true" /> and a top-level model was not bound.
/// </para>
/// <para>
/// For back-compatibility reasons, <see cref="ModelBindingContext.Result" /> must have
/// <see cref="ModelBindingResult.IsModelSet" /> equal to <see langword="true" /> when a
/// top-level model is not bound. Therefore, ParameterBinder can not detect a
/// <see cref="ModelMetadata.IsBindingRequired" /> failure for collections. Add the error here.
/// </para>
/// </remarks>
protected void AddErrorIfBindingRequired(ModelBindingContext bindingContext)
{
var modelMetadata = bindingContext.ModelMetadata;
if (modelMetadata.IsBindingRequired)
{
var messageProvider = modelMetadata.ModelBindingMessageProvider;
var message = messageProvider.MissingBindRequiredValueAccessor(bindingContext.FieldName);
bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, message);
}
}
/// <summary>
/// Create an <see cref="object"/> assignable to <paramref name="targetType"/>.
/// </summary>
/// <param name="targetType"><see cref="Type"/> of the model.</param>
/// <returns>An <see cref="object"/> assignable to <paramref name="targetType"/>.</returns>
/// <remarks>Called when creating a default 'empty' model for a top level bind.</remarks>
protected virtual object CreateEmptyCollection(Type targetType)
{
if (targetType.IsAssignableFrom(typeof(List<TElement>)))
{
// Simple case such as ICollection<TElement>, IEnumerable<TElement> and IList<TElement>.
return new List<TElement>();
}
return CreateInstance(targetType);
}
/// <summary>
/// Create an instance of <paramref name="targetType"/>.
/// </summary>
/// <param name="targetType"><see cref="Type"/> of the model.</param>
/// <returns>An instance of <paramref name="targetType"/>.</returns>
protected object CreateInstance(Type targetType)
{
if (_modelCreator == null)
{
_modelCreator = Expression
.Lambda<Func<object>>(Expression.New(targetType))
.Compile();
}
return _modelCreator();
}
// Used when the ValueProvider contains the collection to be bound as a single element, e.g. the raw value
// is [ "1", "2" ] and needs to be converted to an int[].
// Internal for testing.
internal async Task<CollectionResult> BindSimpleCollection(
ModelBindingContext bindingContext,
ValueProviderResult values)
{
var boundCollection = new List<TElement>();
var elementMetadata = bindingContext.ModelMetadata.ElementMetadata;
foreach (var value in values)
{
bindingContext.ValueProvider = new CompositeValueProvider
{
// our temporary provider goes at the front of the list
new ElementalValueProvider(bindingContext.ModelName, value, values.Culture),
bindingContext.ValueProvider
};
// Enter new scope to change ModelMetadata and isolate element binding operations.
using (bindingContext.EnterNestedScope(
elementMetadata,
fieldName: bindingContext.FieldName,
modelName: bindingContext.ModelName,
model: null))
{
await ElementBinder.BindModelAsync(bindingContext);
if (bindingContext.Result.IsModelSet)
{
var boundValue = bindingContext.Result.Model;
boundCollection.Add(ModelBindingHelper.CastOrDefault<TElement>(boundValue));
}
}
}
return new CollectionResult
{
Model = boundCollection
};
}
// Used when the ValueProvider contains the collection to be bound as multiple elements, e.g. foo[0], foo[1].
private Task<CollectionResult> BindComplexCollection(ModelBindingContext bindingContext)
{
Logger.AttemptingToBindCollectionUsingIndices(bindingContext);
var indexPropertyName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, "index");
// Remove any value provider that may not use indexPropertyName as-is. Don't match e.g. Model[index].
var valueProvider = bindingContext.ValueProvider;
if (valueProvider is IKeyRewriterValueProvider keyRewriterValueProvider)
{
valueProvider = keyRewriterValueProvider.Filter() ?? EmptyValueProvider;
}
var valueProviderResultIndex = valueProvider.GetValue(indexPropertyName);
var indexNames = GetIndexNamesFromValueProviderResult(valueProviderResultIndex);
return BindComplexCollectionFromIndexes(bindingContext, indexNames);
}
// Internal for testing.
internal async Task<CollectionResult> BindComplexCollectionFromIndexes(
ModelBindingContext bindingContext,
IEnumerable<string> indexNames)
{
bool indexNamesIsFinite;
if (indexNames != null)
{
indexNamesIsFinite = true;
}
else
{
indexNamesIsFinite = false;
indexNames = Enumerable.Range(0, int.MaxValue)
.Select(i => i.ToString(CultureInfo.InvariantCulture));
}
var elementMetadata = bindingContext.ModelMetadata.ElementMetadata;
var boundCollection = new List<TElement>();
foreach (var indexName in indexNames)
{
var fullChildName = ModelNames.CreateIndexModelName(bindingContext.ModelName, indexName);
ModelBindingResult? result;
using (bindingContext.EnterNestedScope(
elementMetadata,
fieldName: indexName,
modelName: fullChildName,
model: null))
{
await ElementBinder.BindModelAsync(bindingContext);
result = bindingContext.Result;
}
var didBind = false;
object boundValue = null;
if (result != null && result.Value.IsModelSet)
{
didBind = true;
boundValue = result.Value.Model;
}
// infinite size collection stops on first bind failure
if (!didBind && !indexNamesIsFinite)
{
break;
}
boundCollection.Add(ModelBindingHelper.CastOrDefault<TElement>(boundValue));
}
return new CollectionResult
{
Model = boundCollection,
// If we're working with a fixed set of indexes then this is the format like:
//
// ?parameter.index=zero¶meter.index=one¶meter.index=two¶meter[zero]=0¶meter[one]=1¶meter[two]=2...
//
// We need to provide this data to the validation system so it can 'replay' the keys.
// But we can't just set ValidationState here, because it needs the 'real' model.
ValidationStrategy = indexNamesIsFinite ?
new ExplicitIndexCollectionValidationStrategy(indexNames) :
null,
};
}
// Internal for testing.
internal class CollectionResult
{
public IEnumerable<TElement> Model { get; set; }
public IValidationStrategy ValidationStrategy { get; set; }
}
/// <summary>
/// Gets an <see cref="object"/> assignable to <paramref name="targetType"/> that contains members from
/// <paramref name="collection"/>.
/// </summary>
/// <param name="targetType"><see cref="Type"/> of the model.</param>
/// <param name="collection">
/// Collection of values retrieved from value providers. <see langword="null"/> if nothing was bound.
/// </param>
/// <returns>
/// An <see cref="object"/> assignable to <paramref name="targetType"/>. <see langword="null"/> if nothing
/// was bound.
/// </returns>
/// <remarks>
/// Extensibility point that allows the bound collection to be manipulated or transformed before being
/// returned from the binder.
/// </remarks>
protected virtual object ConvertToCollectionType(Type targetType, IEnumerable<TElement> collection)
{
if (collection == null)
{
return null;
}
if (targetType.IsAssignableFrom(typeof(List<TElement>)))
{
// Depends on fact BindSimpleCollection() and BindComplexCollection() always return a List<TElement>
// instance or null.
return collection;
}
var newCollection = CreateInstance(targetType);
CopyToModel(newCollection, collection);
return newCollection;
}
/// <summary>
/// Adds values from <paramref name="sourceCollection"/> to given <paramref name="target"/>.
/// </summary>
/// <param name="target"><see cref="object"/> into which values are copied.</param>
/// <param name="sourceCollection">
/// Collection of values retrieved from value providers. <see langword="null"/> if nothing was bound.
/// </param>
protected virtual void CopyToModel(object target, IEnumerable<TElement> sourceCollection)
{
if (target == null)
{
throw new ArgumentNullException(nameof(target));
}
var targetCollection = target as ICollection<TElement>;
Debug.Assert(targetCollection != null, "This binder is instantiated only for ICollection<T> model types.");
if (sourceCollection != null && targetCollection != null && !targetCollection.IsReadOnly)
{
targetCollection.Clear();
foreach (var element in sourceCollection)
{
targetCollection.Add(element);
}
}
}
private static IEnumerable<string> GetIndexNamesFromValueProviderResult(ValueProviderResult valueProviderResult)
{
IEnumerable<string> indexNames = null;
if (valueProviderResult != null)
{
var indexes = (string[])valueProviderResult;
if (indexes != null && indexes.Length > 0)
{
indexNames = indexes;
}
}
return indexNames;
}
}
}