简体   繁体   English

如何在ASP.Net Core 2中返回CSV文件?

[英]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. 因此,我只是尝试从.Net Core 2 Web API返回CSV文件。 Each time I do this I get a 406 status code... 每次这样做,我都会得到406状态代码...

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. 我一直在想我需要在Startup.cs文件中添加一个格式化程序或其他东西,但是那也不起作用。

Seems like this should be a simple request, but I am finding the interwebs sparse on this topic. 似乎这应该是一个简单的请求,但是我发现有关此主题的互联网稀疏。

Thanks! 谢谢!

Something like this should work: 这样的事情应该起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM