-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCsvInputFormatter.cs
More file actions
53 lines (44 loc) · 1.72 KB
/
Copy pathCsvInputFormatter.cs
File metadata and controls
53 lines (44 loc) · 1.72 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
namespace CsvToJsonCore
{
// Thanks to https://github.com/RickStrahl/AspNetCoreRawRequestSample for the starting example here.
public class CsvInputFormatter : InputFormatter
{
public CsvInputFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
}
//Accept text/plain and text/csv only
public override Boolean CanRead(InputFormatterContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
var contentType = context.HttpContext.Request.ContentType;
if (contentType == "text/plain" || contentType == "text/csv")
return true;
else
return false;
}
// handle the raw text input
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var request = context.HttpContext.Request;
var contentType = context.HttpContext.Request.ContentType;
if (contentType == "text/csv" || contentType == "text/plain")
{
using (var reader = new StreamReader(request.Body))
{
var content = await reader.ReadToEndAsync();
return await InputFormatterResult.SuccessAsync(content);
}
}
return await InputFormatterResult.FailureAsync();
}
}
}