无法从Web API下载CSV文件

时间:2019-06-06 02:38:10

标签: asp.net-web-api export-to-csv httpresponsemessage

我有这个示例代码来自不同的来源,我想先尝试一下,然后再将其应用于我的代码,这与我获得的示例非常相似。

我的控制器中包含以下代码:

[Route("getcsv")]
    [HttpGet]
    public HttpResponseMessage GetCSV()
    {
        var data = new[]{   //Suppose you filter out these data

                           new{ Name="Ram", Email="ram@techbrij.com", Phone="111-222-3333" },
                           new{ Name="Shyam", Email="shyam@techbrij.com", Phone="159-222-1596" },
                           new{ Name="Mohan", Email="mohan@techbrij.com", Phone="456-222-4569" },
                           new{ Name="Sohan", Email="sohan@techbrij.com", Phone="789-456-3333" },
                           new{ Name="Karan", Email="karan@techbrij.com", Phone="111-222-1234" },
                           new{ Name="Brij", Email="brij@techbrij.com", Phone="111-222-3333" }
                  };

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StringContent(WriteTsv(data));
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); //attachment will force download
        result.Content.Headers.ContentDisposition.FileName = "RecordExport.csv";


        return result;
    }

    public string WriteTsv<T>(IEnumerable<T> data)
    {
        StringBuilder output = new StringBuilder();
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        foreach (PropertyDescriptor prop in props)
        {
            output.Append(prop.DisplayName); // header
            output.Append("\t");
        }
        output.AppendLine();
        foreach (T item in data)
        {
            foreach (PropertyDescriptor prop in props)
            {
                output.Append(prop.Converter.ConvertToString(
                     prop.GetValue(item)));
                output.Append("\t");
            }
            output.AppendLine();
        }
        return output.ToString();
    }

我通过以下方法调用此方法:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script type="text/javascript">
        function save() {
            window.open('https://localhost:44370/api/values/getcsv', '_blank', '');
        }
    </script>
</head>
<body>
    <a class="btn btn-primary" onclick="save()">Export</a>
</body>
</html>

所有这些使我获得了以下结果,而不是下载文件:

enter image description here

我不知道我缺少什么。请帮忙!谢谢!

1 个答案:

答案 0 :(得分:2)

您最有可能为您的Web API版本使用了错误的语法。

如果使用Asp.Net Core Web API,则需要将其重构为

[Route("api/[controller]")]
public class ValuesController: Controller {
    //GET api/values/getcsv
    [Route("getcsv")]
    [HttpGet]
    public IActionResult GetCSV() {
        var data = new[]{   //Suppose you filter out these data
           new{ Name="Ram", Email="ram@techbrij.com", Phone="111-222-3333" },
           new{ Name="Shyam", Email="shyam@techbrij.com", Phone="159-222-1596" },
           new{ Name="Mohan", Email="mohan@techbrij.com", Phone="456-222-4569" },
           new{ Name="Sohan", Email="sohan@techbrij.com", Phone="789-456-3333" },
           new{ Name="Karan", Email="karan@techbrij.com", Phone="111-222-1234" },
           new{ Name="Brij", Email="brij@techbrij.com", Phone="111-222-3333" }
        };

        var bytes = System.Text.Encoding.UTF8.GetBytes(WriteTsv(data));
        return File(bytes, "application/octet-stream", "RecordExport.csv");
    }

    //...code omitted for brevity

}

在Asp.Net Core HttpResponseMessage中,它不再被视为管道的一等公民,并且像普通模型一样被序列化。