8
8
using System . Reflection ;
9
9
using Microsoft . AspNetCore . Mvc . Formatters ;
10
10
using System . ComponentModel . DataAnnotations ;
11
+ using Newtonsoft . Json ;
11
12
12
13
namespace WebApiContrib . Core . Formatter . Csv
13
14
{
@@ -50,6 +51,21 @@ private bool IsTypeOfIEnumerable(Type type)
50
51
51
52
return false ;
52
53
}
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
+ }
53
69
54
70
public async override Task WriteResponseBodyAsync ( OutputFormatterWriteContext context )
55
71
{
@@ -71,22 +87,31 @@ public async override Task WriteResponseBodyAsync(OutputFormatterWriteContext co
71
87
72
88
if ( _options . UseSingleLineHeaderInCsv )
73
89
{
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 ) ) ;
79
96
}
80
97
98
+
81
99
foreach ( var obj in ( IEnumerable < object > ) context . Object )
82
100
{
83
101
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
+ } ) ;
90
115
91
116
string valueLine = string . Empty ;
92
117
0 commit comments