-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryParser.cs
More file actions
57 lines (50 loc) · 1.8 KB
/
QueryParser.cs
File metadata and controls
57 lines (50 loc) · 1.8 KB
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
using System.Reflection;
using System.Text.Json.Serialization;
namespace ModuWeb
{
public class QueryParser
{
/// <summary>
/// Parsring query into T object;
/// </summary>
/// <param name="query">Query of the request</param>
public static T? Parse<T>(IQueryCollection query) where T : new()
{
var obj = new T();
var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in props)
{
string name = prop.Name;
var attr = prop.GetCustomAttribute<JsonPropertyNameAttribute>();
if (attr != null)
name = attr.Name;
if (query.TryGetValue(name, out var value))
{
try
{
object? converted = null;
var type = prop.PropertyType;
var underlyingType = Nullable.GetUnderlyingType(type);
if (underlyingType != null)
{
if (string.IsNullOrWhiteSpace(value.ToString()))
converted = null;
else
converted = Convert.ChangeType(value.ToString(), underlyingType);
}
else
{
converted = Convert.ChangeType(value.ToString(), type);
}
prop.SetValue(obj, converted);
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
}
return obj;
}
}
}