-
Notifications
You must be signed in to change notification settings - Fork 116
/
CsvInputFormatter.cs
133 lines (108 loc) · 4.26 KB
/
CsvInputFormatter.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
using System.Linq;
namespace WebApiContrib.Core.Formatter.Csv
{
/// <summary>
/// ContentType: text/csv
/// </summary>
public class CsvInputFormatter : InputFormatter
{
private readonly CsvFormatterOptions _options;
private readonly bool useJsonAttributes = true;
public CsvInputFormatter(CsvFormatterOptions csvFormatterOptions)
{
SupportedMediaTypes.Add(Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/csv"));
if (csvFormatterOptions == null)
{
throw new ArgumentNullException(nameof(csvFormatterOptions));
}
_options = csvFormatterOptions;
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var type = context.ModelType;
var request = context.HttpContext.Request;
MediaTypeHeaderValue requestContentType = null;
MediaTypeHeaderValue.TryParse(request.ContentType, out requestContentType);
var result = await ReadStreamAsync(type, request.Body);
return await InputFormatterResult.SuccessAsync(result);
}
protected override bool CanReadType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return IsTypeOfIEnumerable(type);
}
private bool IsTypeOfIEnumerable(Type type)
{
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType == typeof(IList))
return true;
}
return false;
}
protected async Task<object> ReadStreamAsync(Type type, Stream stream)
{
Type itemType;
var typeIsArray = false;
IList list;
if (type.GetGenericArguments().Length > 0)
{
itemType = type.GetGenericArguments()[0];
list = (IList)Activator.CreateInstance(type);
}
else
{
typeIsArray = true;
itemType = type.GetElementType();
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(itemType);
list = (IList)Activator.CreateInstance(constructedListType);
}
var reader = new StreamReader(stream, _options.Encoding);
bool skipFirstLine = _options.UseSingleLineHeaderInCsv;
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
var values = line.Split(_options.CsvDelimiter.ToCharArray());
if (skipFirstLine)
{
skipFirstLine = false;
}
else
{
var itemTypeInGeneric = list.GetType().GetTypeInfo().GenericTypeArguments[0];
var item = Activator.CreateInstance(itemTypeInGeneric);
var properties = useJsonAttributes
? item.GetType().GetProperties().Where(pi => !pi.GetCustomAttributes<JsonIgnoreAttribute>().Any()).ToArray()
: item.GetType().GetProperties();
for (int i = 0; i < values.Length; i++)
{
properties[i].SetValue(item, Convert.ChangeType(values[i], properties[i].PropertyType), null);
}
list.Add(item);
}
}
if (typeIsArray)
{
Array array = Array.CreateInstance(itemType, list.Count);
for (int t = 0; t < list.Count; t++)
{
array.SetValue(list[t], t);
}
return array;
}
return list;
}
}
}