Skip to content

Commit 92987ff

Browse files
authored
Merge pull request #132 from lukaszadamus/master
Add MvcCoreBuilderExtensions
2 parents 1c8c6a3 + eab3a3f commit 92987ff

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
using Microsoft.Extensions.DependencyInjection;
2+
using Microsoft.Net.Http.Headers;
3+
using System;
4+
5+
namespace WebApiContrib.Core.Formatter.Csv
6+
{
7+
public static class CsvFormatterMvcCoreBuilderExtensions
8+
{
9+
public static IMvcCoreBuilder AddCsvSerializerFormatters(this IMvcCoreBuilder builder)
10+
{
11+
if (builder == null)
12+
{
13+
throw new ArgumentNullException(nameof(builder));
14+
}
15+
16+
return AddCsvSerializerFormatters(builder, csvFormatterOptions: null);
17+
}
18+
19+
public static IMvcCoreBuilder AddCsvSerializerFormatters(this IMvcCoreBuilder builder, CsvFormatterOptions csvFormatterOptions)
20+
{
21+
if (builder == null)
22+
{
23+
throw new ArgumentNullException(nameof(builder));
24+
}
25+
26+
builder.AddFormatterMappings(m => m.SetMediaTypeMappingForFormat("csv", new MediaTypeHeaderValue("text/csv")));
27+
28+
if (csvFormatterOptions == null)
29+
{
30+
csvFormatterOptions = new CsvFormatterOptions();
31+
}
32+
33+
if (string.IsNullOrWhiteSpace(csvFormatterOptions.CsvDelimiter))
34+
{
35+
throw new ArgumentException("CsvDelimiter cannot be empty");
36+
}
37+
38+
builder.AddMvcOptions(options => options.InputFormatters.Add(new CsvInputFormatter(csvFormatterOptions)));
39+
builder.AddMvcOptions(options => options.OutputFormatters.Add(new CsvOutputFormatter(csvFormatterOptions)));
40+
41+
return builder;
42+
}
43+
}
44+
}

0 commit comments

Comments
 (0)