Skip to content

Commit 9b4e7b8

Browse files
committed
merge
1 parent fb4d9c0 commit 9b4e7b8

File tree

1 file changed

+36
-11
lines changed

1 file changed

+36
-11
lines changed

src/WebApiContrib.Core.Formatter.Csv/CsvOutputFormatter.cs

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using System.Reflection;
99
using Microsoft.AspNetCore.Mvc.Formatters;
1010
using System.ComponentModel.DataAnnotations;
11+
using Newtonsoft.Json;
1112

1213
namespace WebApiContrib.Core.Formatter.Csv
1314
{
@@ -50,6 +51,21 @@ private bool IsTypeOfIEnumerable(Type type)
5051

5152
return false;
5253
}
54+
55+
/// <summary>
56+
/// Returns the JsonProperty data annotation name
57+
/// </summary>
58+
/// <param name="pi">Property Info</param>
59+
/// <returns></returns>
60+
private string GetDisplayNameFromNewtonsoftJsonAnnotations(PropertyInfo pi)
61+
{
62+
if (pi.GetCustomAttribute<JsonPropertyAttribute>(false)?.PropertyName is string value)
63+
{
64+
return value;
65+
}
66+
67+
return pi.GetCustomAttribute<DisplayAttribute>(false)?.Name ?? pi.Name;
68+
}
5369

5470
public async override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
5571
{
@@ -71,22 +87,31 @@ public async override Task WriteResponseBodyAsync(OutputFormatterWriteContext co
7187

7288
if (_options.UseSingleLineHeaderInCsv)
7389
{
74-
await streamWriter.WriteLineAsync(
75-
string.Join(
76-
_options.CsvDelimiter, itemType.GetProperties().Select(x => x.GetCustomAttribute<DisplayAttribute>(false)?.Name ?? x.Name)
77-
)
78-
);
90+
var values = _options.UseJsonPropertyJsonIgnoreAttributes
91+
? itemType.GetProperties().Where(pi => !pi.GetCustomAttributes<JsonIgnoreAttribute>(false).Any()) // Only get the properties that do not define JsonIgnore
92+
.Select(GetDisplayNameFromNewtonsoftJsonAnnotations)
93+
: itemType.GetProperties().Select(pi => pi.GetCustomAttribute<DisplayAttribute>(false)?.Name ?? pi.Name);
94+
95+
await streamWriter.WriteLineAsync(string.Join(_options.CsvDelimiter, values));
7996
}
8097

98+
8199
foreach (var obj in (IEnumerable<object>)context.Object)
82100
{
83101

84-
var vals = obj.GetType().GetProperties().Select(
85-
pi => new
86-
{
87-
Value = pi.GetValue(obj, null)
88-
}
89-
);
102+
//IEnumerable<ObjectValue> vals;
103+
var vals = _options.UseJsonPropertyJsonIgnoreAttributes
104+
? obj.GetType().GetProperties()
105+
.Where(pi => !pi.GetCustomAttributes<JsonIgnoreAttribute>().Any())
106+
.Select(pi => new
107+
{
108+
Value = pi.GetValue(obj, null)
109+
})
110+
: obj.GetType().GetProperties().Select(
111+
pi => new
112+
{
113+
Value = pi.GetValue(obj, null)
114+
});
90115

91116
string valueLine = string.Empty;
92117

0 commit comments

Comments
 (0)