Array of strings property of my class is not coming up in the csv

98 Views Asked by At

I am using CsvHelper (ver: 27.2.1). I have a Get API and i am trying to enable text/csv Accept header. So that when I initiate a Get Request from Postman with Accept header as text/csv, I get a CSV response. So I created a CSV output formatter and added to my outputforamtters collection in Program.cs.

The piece of code below is working fine except that in my response csv i am not getting the Roles header or the value. It's completely ignored.

I tried creating a Map and use it with RegisterClassMap but when i do that the api itself stops working. I mean as soon as i introduce

csvWriter.Context.RegisterClassMap<CSVMap>();

in WriteResponseBodyAsync method. The api stops returning csv result.

I have a class with multiple properties.

public class Employee {
 public string Name{get;set;}
 public string[] Roles {get;set;}
 public Employer company {get;set;}
}

public class Employer{
 public string EmpPloyerName {get;set;}
}

My CsvOutputFormatter looks like below ---------->

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(IEnumerable).IsAssignableFrom(type))
            {
                return base.CanWriteType(type);
            }
            return false;
        }
       
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            var streamWriter = new StreamWriter(context.HttpContext.Response.Body, selectedEncoding, leaveOpen: true);

            await using (var csvWriter = new CsvWriter(streamWriter, new CsvConfiguration(System.Globalization.CultureInfo.InvariantCulture)))
            {
                //csvWriter.Context.RegisterClassMap<CSVMap>();
                await csvWriter.WriteRecordsAsync((IEnumerable)context.Object);
            }
        }
        


     public class CSVMap : ClassMap<Employee>
        {
            public CSVMap()
            {
                AutoMap(System.Globalization.CultureInfo.InvariantCulture);
                Map(m => m.Roles).Convert(row => string.Join(",", row.Value.Roles));
            }
        }

    

Output Formatter registering in Program.cs--->

  builder.Services.AddControllers(
     options =>
  {
     options.RespectBrowserAcceptHeader = true;
     options.OutputFormatters.Add(new CsvOutputFormatter());

  });
0

There are 0 best solutions below