-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSVOutputFormatter.cs
54 lines (47 loc) · 1.64 KB
/
CSVOutputFormatter.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
using Entities.DTOs;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace CompanyEmployee
{
public class CsvOutputFormatter : TextOutputFormatter
{
public CsvOutputFormatter()
{
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/csv"));
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
}
protected override bool CanWriteType(Type type)
{
if (typeof(CompanyDto).IsAssignableFrom(type) || typeof(IEnumerable<CompanyDto>).IsAssignableFrom(type))
{
return base.CanWriteType(type);
}
return false;
}
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
var response = context.HttpContext.Response;
var buffer = new StringBuilder();
if (context.Object is IEnumerable<CompanyDto> companyDtos)
{
foreach (var companyDto in companyDtos)
FormatCsv(buffer, companyDto);
}
else
{
FormatCsv(buffer, (CompanyDto)context.Object);
}
await response.WriteAsync(buffer.ToString());
}
private static void FormatCsv(StringBuilder buffer, CompanyDto company)
{
buffer.AppendLine($"{company.Id},\"{company.Name},\"{company.FullAddress}\"");
}
}
}