ASP.NET Core 2 Controller's ActionMethod async Task<FileResult> returns HttpresponseMessage

1.2k Views Asked by At

UPDATE: As I mentioned I changed my action method, no success. See screenshots

enter image description here

The result is the same, no matter:

enter image description here

Briefly summarising my problem: Everything is in dot net core 2.0. I have a WebAPI (separate project) and its Controller (talking to an SQL Server). My client App is an ASP.NET Core MVC web app its controller's action method WOULD return a file. In my case a stream of bytes. When I open the file which I downloaded from the browser running my client app, the file is like some HttpResponseMessage wrapped in JSON style format.


API Controller

[Route("api/[controller]")]
public class GasDownloadController : Controller
{
    private readonly IGasesRepository _repository;

    public GasDownloadController(IGasesRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public HttpResponseMessage Export([FromQuery] Gas gas)
    {
        var item = _repository.GetGasesService(gas);

        byte[] outputBuffer = null;

        using (MemoryStream tempStream = new MemoryStream())
        {
            using (StreamWriter writer = new StreamWriter(tempStream))
            {
                FileWriter.WriteDataTable(item, writer, true);
            }
            outputBuffer = tempStream.ToArray();
        }
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(outputBuffer);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = $"ENVSdata.csv" };

        return result;
    }
}

Helper class

public class FileWriter
{
    public static void WriteDataTable(DataTable sourceTable, TextWriter writer, bool includeHeaders)
    {
        if (includeHeaders)
        {
            writer.WriteLine("sep=,");
            IEnumerable<string> headerValues = sourceTable.Columns
                .OfType<DataColumn>()
                .Select(column => QuoteValue(column.ColumnName));
            writer.WriteLine(String.Join(",", headerValues));
        }

        IEnumerable<String> items = null;

        foreach (DataRow row in sourceTable.Rows)
        {
            items = row.ItemArray.Select(o => QuoteValue(o?.ToString() ?? String.Empty));
            writer.WriteLine(String.Join(",", items));
        }

        writer.Flush();
    }
    private static string QuoteValue(string value)
    {
        return String.Concat("\"",
            value.Replace("\"", "\"\""), "\"");
    }
}

MVC Controller

public class DownloadsController : Controller
{
    private IGasesRepository _repository;

    public DownloadsController(IGasesRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }


    [HttpPost]
    public async Task<FileResult> GetFile(Gas inputGas)
    {
        var model = await _repository.GasDownloads(inputGas);
        return File(model, "text/csv", "data.csv");
    }
}

Repo

public class GasesRepository : IGasesRepository
{
    public IEnumerable<Gas> Gases { get; set; }
    public byte[] CsvBytes { get; set; }

    private string BaseGasApiUrl = "http://localhost:XXXX";
    private string BaseDwnlApiUrl = "http://localhost:XXXX";

    public async Task<IEnumerable<Gas>> GasService(Gas gasCompound)
    {
       //code omitted for brewity
    }


    public async Task<byte[]> GasDownloads(Gas gasCompound)
    {
        UriBuilder builder = new UriBuilder(BaseDwnlApiUrl);
        builder.Query =
            $"XXXXX";

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(BaseDwnlApiUrl);
            client.DefaultRequestHeaders.Accept.Clear();

            try
            {
                HttpResponseMessage responseMessage = await client.GetAsync(builder.Uri);

                if (responseMessage.IsSuccessStatusCode)
                {
                    var apiResult = responseMessage.Content.ReadAsByteArrayAsync().Result;

                    CsvBytes = apiResult;
                }
                else
                    return null;
            }
            catch (HttpRequestException downloadRequestException)
            {
                throw new HttpRequestException(downloadRequestException.Message);
            }
            catch (ArgumentNullException argsNullException)
            {
                throw new ArgumentNullException(argsNullException.Message);
            }
        }
        return CsvBytes;
    }
}

THE RESULT

So, when I open the file (f.ex: Excel) which my browser downloaded, it is a CSV file, but instead of columns and rows and the data in it, it is only a

    {
  "version": {
    "major": 1,
    "minor": 1,
    "build": -1,
    "revision": -1,
    "majorRevision": -1,
    "minorRevision": -1
  },
  "content": {
    "headers": [
      {
        "key": "Content-Type",
        "value": [
          "text\/csv"
        ]
      },
      {
        "key": "Content-Disposition",
        "value": [
          "attachment; filename=data.csv"
        ]
      }
    ]
  },
  "statusCode": 200,
  "reasonPhrase": "OK",
  "headers": [

  ],
  "requestMessage": null,
  "isSuccessStatusCode": true
}

What I have already tried:

If I debug I can see I am getting a legal/valid byte array, but somehow some magic happens, or it is so obvious and big that I can't see the wood for the trees?

I tried to change my MVC controller Action method to return many possible types of things (IActionResult, IHttpResponse, FileContentResult, etc...).

I had the same project in MVC 5 and no problem, getting a valid CSV file with my data rows and columns.

Any help would be greatly appreciated!

0

There are 0 best solutions below