1

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!

2 Answers 2

9

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Consider using UTF8 rather than ASCII if the data may contain a wider set of characters or user generated content to avoid conversion issues.
0
    [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;
    }

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.