web-dev-qa-db-fra.com

Comment exporter un fichier CSV à partir du noyau ASP.NET

J'essaie de migrer le code d'ASP.net vers le noyau ASP.net.

Où comme dans le code ASP.net était comme ci-dessous,

var progresses = db.Progresses.Where(p => p.UserId == id).Include(p => p.User.UserMetaData).Include(p => p.Quiz).Include(p => p.User.Groups).OrderByDescending(p => p.UpdatedAt).ToList();

List<ReportCSVModel> reportCSVModels = new List<ReportCSVModel>();
const string downloadName = "Reports.csv";
var csv = new CsvWriter(Response.Output);

csv.Configuration.RegisterClassMap<ReportCSVMap>();

Response.ClearContent();

Response.ContentType = "application/octet-stream";

Response.AddHeader("Content-Disposition",
   "attachment; filename=" + downloadName);

csv.WriteHeader<ReportCSVModel>();
foreach (var progress in progresses)
{
    var reportCSVModel = new ReportCSVModel();
    reportCSVModel.Quiz = progress.Quiz.Title;
    reportCSVModel.Score = (progress.CorrectAnswersCount * progress.PointsPerQuestion).ToString();
    reportCSVModel.Status = progress.Status;
    reportCSVModel.CompletedDate = progress.UpdatedAt.ToString();
    reportCSVModel.Location = progress.User.UserMetaData != null ? progress.User.UserMetaData.Location : "";
    reportCSVModel.Group = progress.User.Groups.FirstOrDefault() != null ? progress.User.Groups.FirstOrDefault().Name : "";

    csv.WriteRecord<ReportCSVModel>(reportCSVModel);
}
Response.Flush();
Response.End();
return null;

Mais en l'utilisant dans le noyau ASP.NET, je l'ai converti comme,

var progresses = _elearnContext.Progress.Where(p => p.UserId == id).Include(p => p.User.UserMetaData).Include(p => p.Quiz).Include(p => p.User.Groups).OrderByDescending(p => p.UpdatedAt).ToList();

// List<ReportCSVModel> reportCSVModels = new List<ReportCSVModel>();
List<ReportCSVModel> reportCSVModels = new List<ReportCSVModel>();
const string downloadName = "Reports.csv";

System.IO.TextWriter writeFile = new StreamWriter(Response.Body.ToString());
CsvWriter csv = new CsvWriter(writeFile);
csv.Configuration.RegisterClassMap<GroupReportCSVMap>();
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.Headers.Add("Content-Disposition", "attachment; filename=" + downloadName);


csv.WriteHeader<ReportCSVModel>();
foreach (var progress in progresses)
{
    var reportCSVModel = new ReportCSVModel();
    reportCSVModel.Quiz = progress.Quiz.Title;
    reportCSVModel.Score = (progress.CorrectAnswersCount * progress.PointsPerQuestion).ToString();
    reportCSVModel.Status = progress.Status;
    reportCSVModel.CompletedDate = progress.UpdatedAt.ToString();
    reportCSVModel.Location = progress.User.UserMetaData != null ? progress.User.UserMetaData.Location : "";
    reportCSVModel.Group = progress.User.Groups.FirstOrDefault() != null ? progress.User.Groups.FirstOrDefault().Name : "";

    csv.WriteRecord<ReportCSVModel>(reportCSVModel);
}

Response.Clear();
return null;

Dans ASP.net où Response.Output est disponible mais n'est pas disponible dans le noyau. J'ai donc essayé de l'utiliser comme Response.Body

Quelqu'un peut-il me dire où je me suis trompé?

3
Rohit Borude

Envisagez de changer d'approche pour vous aligner davantage sur la syntaxe actuellement suggérée.

Construisez le CSV et renvoyez un FileResult, qui permet au code de ne pas avoir à manipuler directement l'objet Response.

[HttpGet]
public IActionResult MyExportAction() {
    var progresses = _elearnContext.Progress.Where(p => p.UserId == id)
        .Include(p => p.User.UserMetaData)
        .Include(p => p.Quiz)
        .Include(p => p.User.Groups)
        .OrderByDescending(p => p.UpdatedAt)
        .ToList()
        .Select(progress => 
            new ReportCSVModel() {
                Quiz = progress.Quiz.Title,
                Score = (progress.CorrectAnswersCount * progress.PointsPerQuestion).ToString(),
                Status = progress.Status,
                CompletedDate = progress.UpdatedAt.ToString(),
                Location = progress.User.UserMetaData != null ? progress.User.UserMetaData.Location : "",
                Group = progress.User.Groups.FirstOrDefault() != null ? progress.User.Groups.FirstOrDefault().Name : ""
            }
        );

    List<ReportCSVModel> reportCSVModels = progresses.ToList();

    var stream = new MemoryStream();
    using(var writeFile = new StreamWriter(stream, leaveOpen: true)) {
        var csv = new CsvWriter(writeFile, true);
        csv.Configuration.RegisterClassMap<GroupReportCSVMap>();            
        csv.WriteRecords(reportCSVModels);
    }
    stream.Position = 0; //reset stream
    return File(stream, "application/octet-stream", "Reports.csv");
}
8
Nkosi