-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
FormFileModelBinder.cs
214 lines (184 loc) · 7.49 KB
/
FormFileModelBinder.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
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
/// <summary>
/// <see cref="IModelBinder"/> implementation to bind posted files to <see cref="IFormFile"/>.
/// </summary>
public partial class FormFileModelBinder : IModelBinder
{
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of <see cref="FormFileModelBinder"/>.
/// </summary>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
public FormFileModelBinder(ILoggerFactory loggerFactory)
{
ArgumentNullException.ThrowIfNull(loggerFactory);
_logger = loggerFactory.CreateLogger<FormFileModelBinder>();
}
/// <inheritdoc />
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
ArgumentNullException.ThrowIfNull(bindingContext);
_logger.AttemptingToBindModel(bindingContext);
var createFileCollection = bindingContext.ModelType == typeof(IFormFileCollection);
if (!createFileCollection && !ModelBindingHelper.CanGetCompatibleCollection<IFormFile>(bindingContext))
{
// Silently fail if unable to create an instance or use the current instance.
return;
}
ICollection<IFormFile> postedFiles;
if (createFileCollection)
{
postedFiles = new List<IFormFile>();
}
else
{
postedFiles = ModelBindingHelper.GetCompatibleCollection<IFormFile>(bindingContext);
}
// If we're at the top level, then use the FieldName (parameter or property name).
// This handles the fact that there will be nothing in the ValueProviders for this parameter
// and so we'll do the right thing even though we 'fell-back' to the empty prefix.
var modelName = bindingContext.IsTopLevelObject
? bindingContext.BinderModelName ?? bindingContext.FieldName
: bindingContext.ModelName;
await GetFormFilesAsync(modelName, bindingContext, postedFiles);
// If ParameterBinder incorrectly overrode ModelName, fall back to OriginalModelName prefix. Comparisons
// are tedious because e.g. top-level parameter or property is named Blah and it contains a BlahBlah
// property. OriginalModelName may be null in tests.
if (postedFiles.Count == 0 &&
bindingContext.OriginalModelName != null &&
!string.Equals(modelName, bindingContext.OriginalModelName, StringComparison.Ordinal) &&
!modelName.StartsWith(bindingContext.OriginalModelName + "[", StringComparison.Ordinal) &&
!modelName.StartsWith(bindingContext.OriginalModelName + ".", StringComparison.Ordinal))
{
modelName = ModelNames.CreatePropertyModelName(bindingContext.OriginalModelName, modelName);
await GetFormFilesAsync(modelName, bindingContext, postedFiles);
}
object value;
if (bindingContext.ModelType == typeof(IFormFile))
{
if (postedFiles.Count == 0)
{
// Silently fail if the named file does not exist in the request.
_logger.DoneAttemptingToBindModel(bindingContext);
return;
}
value = postedFiles.First();
}
else
{
if (postedFiles.Count == 0 && !bindingContext.IsTopLevelObject)
{
// Silently fail if no files match. Will bind to an empty collection (treat empty as a success
// case and not reach here) if binding to a top-level object.
_logger.DoneAttemptingToBindModel(bindingContext);
return;
}
// Perform any final type mangling needed.
var modelType = bindingContext.ModelType;
if (modelType == typeof(IFormFile[]))
{
Debug.Assert(postedFiles is List<IFormFile>);
value = ((List<IFormFile>)postedFiles).ToArray();
}
else if (modelType == typeof(IFormFileCollection))
{
Debug.Assert(postedFiles is List<IFormFile>);
value = new FileCollection((List<IFormFile>)postedFiles);
}
else
{
value = postedFiles;
}
}
// We need to add a ValidationState entry because the modelName might be non-standard. Otherwise
// the entry we create in model state might not be marked as valid.
bindingContext.ValidationState.Add(value, new ValidationStateEntry()
{
Key = modelName,
});
bindingContext.ModelState.SetModelValue(
modelName,
rawValue: null,
attemptedValue: null);
bindingContext.Result = ModelBindingResult.Success(value);
_logger.DoneAttemptingToBindModel(bindingContext);
}
private async Task GetFormFilesAsync(
string modelName,
ModelBindingContext bindingContext,
ICollection<IFormFile> postedFiles)
{
var request = bindingContext.HttpContext.Request;
if (request.HasFormContentType)
{
var form = await request.ReadFormAsync();
foreach (var file in form.Files)
{
// If there is an <input type="file" ... /> in the form and is left blank.
if (file.Length == 0 && string.IsNullOrEmpty(file.FileName))
{
continue;
}
if (file.Name.Equals(modelName, StringComparison.OrdinalIgnoreCase))
{
postedFiles.Add(file);
}
}
if (postedFiles.Count == 0)
{
Log.NoFilesFoundInRequest(_logger);
}
}
else
{
_logger.CannotBindToFilesCollectionDueToUnsupportedContentType(bindingContext);
}
}
private sealed class FileCollection : ReadOnlyCollection<IFormFile>, IFormFileCollection
{
public FileCollection(List<IFormFile> list)
: base(list)
{
}
public IFormFile? this[string name] => GetFile(name);
public IFormFile? GetFile(string name)
{
for (var i = 0; i < Items.Count; i++)
{
var file = Items[i];
if (string.Equals(name, file.Name, StringComparison.OrdinalIgnoreCase))
{
return file;
}
}
return null;
}
public IReadOnlyList<IFormFile> GetFiles(string name)
{
var files = new List<IFormFile>();
for (var i = 0; i < Items.Count; i++)
{
var file = Items[i];
if (string.Equals(name, file.Name, StringComparison.OrdinalIgnoreCase))
{
files.Add(file);
}
}
return files;
}
}
private static partial class Log
{
[LoggerMessage(21, LogLevel.Debug, "No files found in the request to bind the model to.", EventName = "NoFilesFoundInRequest")]
public static partial void NoFilesFoundInRequest(ILogger logger);
}
}