-
Notifications
You must be signed in to change notification settings - Fork 9.9k
/
JQueryFormValueProviderFactory.cs
61 lines (51 loc) · 2.14 KB
/
JQueryFormValueProviderFactory.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
// 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.Globalization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Core;
namespace Microsoft.AspNetCore.Mvc.ModelBinding;
/// <summary>
/// An <see cref="IValueProviderFactory"/> for <see cref="JQueryFormValueProvider"/>.
/// </summary>
public class JQueryFormValueProviderFactory : IValueProviderFactory
{
/// <inheritdoc />
public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
{
ArgumentNullException.ThrowIfNull(context);
var request = context.ActionContext.HttpContext.Request;
if (request.HasFormContentType)
{
// Allocating a Task only when the body is form data.
return AddValueProviderAsync(context);
}
return Task.CompletedTask;
}
private static async Task AddValueProviderAsync(ValueProviderFactoryContext context)
{
var request = context.ActionContext.HttpContext.Request;
IFormCollection formCollection;
try
{
formCollection = await request.ReadFormAsync();
}
catch (InvalidDataException ex)
{
// ReadFormAsync can throw InvalidDataException if the form content is malformed.
// Wrap it in a ValueProviderException that the CompositeValueProvider special cases.
throw new ValueProviderException(Resources.FormatFailedToReadRequestForm(ex.Message), ex);
}
catch (IOException ex)
{
// ReadFormAsync can throw IOException if the client disconnects.
// Wrap it in a ValueProviderException that the CompositeValueProvider special cases.
throw new ValueProviderException(Resources.FormatFailedToReadRequestForm(ex.Message), ex);
}
var valueProvider = new JQueryFormValueProvider(
BindingSource.Form,
JQueryKeyValuePairNormalizer.GetValues(formCollection, formCollection.Count),
CultureInfo.CurrentCulture);
context.ValueProviders.Add(valueProvider);
}
}