-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonPropertyQueryModelBinder.cs
90 lines (85 loc) · 3.39 KB
/
JsonPropertyQueryModelBinder.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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json;
namespace WebApiCore.AspNetCore.Mvc
{
/// <summary>
/// Bind properties to model from query string
/// </summary>
public class JsonPropertyQueryModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
throw new ArgumentNullException(nameof(bindingContext));
Dictionary<PropertyInfo, string> modelProps = new Dictionary<PropertyInfo, string>();
foreach (var prop in bindingContext.ModelType.GetProperties())
{
var jp = prop.GetCustomAttributes<JsonPropertyNameAttribute>().FirstOrDefault();
if (jp != null)
modelProps.Add(prop, jp.Name);
else
{
var njp = prop.GetCustomAttributes<JsonPropertyAttribute>().FirstOrDefault();
if (njp != null)
modelProps.Add(prop, njp.PropertyName);
else
modelProps.Add(prop, prop.Name);
}
}
var model = Activator.CreateInstance(bindingContext.ModelType, true);
foreach (var prop in modelProps)
{
var val = bindingContext.ValueProvider.GetValue(prop.Value);
if (val.Length > 0)
{
TypeConverter converter;
if (prop.Key.PropertyType.IsArray)
{
var propElementType = prop.Key.PropertyType.GetElementType();
converter = TypeDescriptor.GetConverter(propElementType);
var values = Array.CreateInstance(propElementType, val.Length);
bool success = true;
for (int i = 0; i < val.Length; i++)
{
try
{
values.SetValue(converter.ConvertFrom(val.Values.ElementAt(i)), i);
}
catch
{
success = false;
break;
}
}
if (success)
{
prop.Key.SetValue(model, values);
continue;
}
}
else
{
converter = TypeDescriptor.GetConverter(prop.Key.PropertyType);
try
{
prop.Key.SetValue(model, converter.ConvertFrom(val.Values.Last()));
continue;
}
catch
{ }
}
bindingContext.ModelState.TryAddModelError(prop.Value, $"The value \"{prop.Value}\" is not valid.");
}
}
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}
}
}