David
David

Reputation: 2223

How can I return a CSV file in ASP.Net Core 2?

Ok, I thought I had this working, but... no. :)

So I am simply trying to return a CSV file from my .Net Core 2 Web API. Each time I do this I get a 406 status code...

Here is my code.

    [HttpGet]
    [Route("/progress/data.csv")]
    [Produces("text/csv")]
    public IActionResult GetCSV()
    {
        try
        {
            return Ok("1,2,3");
        }
        catch (Exception ex)
        {
            HandleError(ex);
            return BadRequest(ex);
        }
    }

I keep thinking I need to add a formatter or something in my Startup.cs file, but that hasn't worked either.

Seems like this should be a simple request, but I am finding the interwebs sparse on this topic.

Thanks!

Upvotes: 1

Views: 8876

Answers (2)

Marcel
Marcel

Reputation: 1109

Something like this should work:

StringBuilder sb = new StringBuilder();
sb.AppendLine("1;2;3;");
sb.AppendLine("4;5;6;");
return File(System.Text.Encoding.UTF8.GetBytes(sb.ToString()), "text/csv", "data.csv");

Upvotes: 9

    [HttpGet]
    [AllowAnonymous]
    public HttpResponseMessage DowloadTemplate()
    {
        var builder = new StringBuilder();
        builder.AppendLine("Tipo;Chave");
        builder.AppendLine("email;teste");
        builder.AppendLine("telfone;999999999");

        var file = System.Text.Encoding.GetEncoding("Windows-1252").GetBytes(builder.ToString());
        Stream stream = new MemoryStream(file);

        var result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "TemplateTeste.csv";
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");

        return result;
    }

Upvotes: 0

Related Questions