Thomas Raj
Thomas Raj

Reputation: 569

ASP.NET CORE Web API Fails to return file but instead it returns text

I have to export the list users as a CSV file.

Here is my Sample.cs

   `public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public DateTime DateOfBirth { get; set; }`

Here is my controller code and sample data.

   `
  private IList<Sample> sample = new List<Sample>
    {
        new Sample {Id=1,Name ="pons",Email="[email protected]"},
        new Sample {Id=2 ,Name="maddy",Email="[email protected]"},
        new Sample {Id=3,Name="thom",Email="[email protected]"},
        new Sample {Id=4,Name="gomz",Email="[email protected]"},
        new Sample { Id=5,Name="vaandu",Email="[email protected]"}
    };
   [HttpGet]
    [Route("GetValue")]
    public IActionResult ExportToCSV()
    {

        var builder = new StringBuilder();
        builder.AppendLine("Id,Name,Email");
        foreach (var data in sample)
        {
            builder.AppendLine($"{data.Id},{data.Name},{data.Email}");
        }
        return File(Encoding.UTF8.GetBytes(builder.ToString()), "text/csv", "god.csv");`

The above code is expected to return a file (automatically download a csv file).It returns a text instead of a file. Here is the output of the above code Response to postman by above controller

This how it return to my angular request Response b y the above controller to angular request

Upvotes: 1

Views: 431

Answers (2)

Thomas Raj
Thomas Raj

Reputation: 569

Instead of returning a file from ApiController, I returned a list as Response to angular,displayed it in a table and exported that table using table exporter package.

Table exporter implementation

For Angular version more than 9(up to 12) Don't forget to add matTableExporter attribute as below

<table mat-table [dataSource]="dataSource" matSort matTableExporter #exporter="matTableExporter">

This satisfied my requirement.

Upvotes: 0

Malvik Bhavsar
Malvik Bhavsar

Reputation: 440

It should be FileContentResult instead of IActionResult

[HttpGet]
[Route("GetValue")]
public FileContentResult ExportToCSV()
{

    var builder = new StringBuilder();
    builder.AppendLine("Id,Name,Email");
    foreach (var data in sample)
    {
        builder.AppendLine($"{data.Id},{data.Name},{data.Email}");
    }
    return File(Encoding.UTF8.GetBytes(builder.ToString()), "text/csv", "god.csv");`

Upvotes: 2

Related Questions