Aspnet核心3-如何从控制器返回作为字符串生成器创建的文本或csv文件?

问题描述

我已经从数据表中生成一个文本文件,我想使用控制器操作返回将其导出为.txt或.csv文件。在aspx中,我可以使用:

  Cars.OrderByDescending(c => c.ReleaseDate).Take(100).ToList()
    .GroupBy(c => c.ManufacturerId).Select(g => g.First()).Take(5)

结果是一个文本文件用户可以将其保存到硬盘中。

如何使用Aspnet core 3做到这一点?

解决方法

据我所知,在asp.net核心中,我们可以使用FileResult生成下载文本文件的响应。

FileResult将自动为附件提供正确的Content-Disposition标头。

更多详细信息,您可以参考以下测试演示代码:

        public class Student
        {
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
        public IActionResult DownloadCommaSeperatedFile()
        {
            List<Student> students = new List<Student>
{
    new Student { Id = 1,FirstName = "Joydip",LastName = "Kanjilal" },new Student { Id = 2,FirstName = "Steve",LastName = "Smith" },new Student { Id = 3,FirstName = "Anand",LastName = "Narayaswamy"}
};
            try
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("Id,FirstName,LastName");
                foreach (var student in students)
                {
                    stringBuilder.AppendLine($"{student.Id},{ student.FirstName},{ student.LastName}");
                }
                return File(Encoding.UTF8.GetBytes
                (stringBuilder.ToString()),"text/csv","student.csv");
            }
            catch
            {
                return Error();
            }
        }

结果:

enter image description here