I am trying to create an endpoint that accepts a CSV file but the data stream doesn't return any records.
This is my view model:
public class BulkUploadViewModel
{
[Required]
public IFormFile JobCsv { get; set; }
[Required]
public string UserId { get; set; }
}
And this is my endpoint:
[Route("BulkUpload")]
[HttpPost]
public async Task<IActionResult> BulkUpload(BulkUploadViewModel bulkUpload)
{
if(!ModelState.IsValid)
{
return BadRequest();
}
List<BulkUploadDataModel> bulkList = new List<BulkUploadDataModel>();
using (var memoryStream = new MemoryStream())
{
await bulkUpload.JobCsv.CopyToAsync(memoryStream);
TextReader textReader = new StreamReader(memoryStream);
var csv = new CsvReader(textReader);
csv.Configuration.HasHeaderRecord = true;
bulkList = csv.GetRecords<BulkUploadDataModel>().ToList();
}
return Ok(bulkList.Count());
}
I have also tried reading the CSV line by line but Csv.Read()
returns false. I am not sure how to debug this.
I am generating the post with postman:
In the debugger I can see the file name and length value are populated correctly in bulkUpload.JobCsv
so I assume my error is in how I am accessing the stream.
What did I do wrong?
You are just missing memoryStream.Position = 0
after
await bulkUpload.JobCsv.CopyToAsync(memoryStream);
.
like this:
await bulkUpload.JobCsv.CopyToAsync(memoryStream);
memoryStream.Position = 0;
TextReader textReader = new StreamReader(memoryStream);