Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc Web API返回csv文件_Asp.net Mvc_Asp.net Mvc 3_Asp.net Mvc 4_Asp.net Web Api - Fatal编程技术网

Asp.net mvc Web API返回csv文件

Asp.net mvc Web API返回csv文件,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,asp.net-web-api,Asp.net Mvc,Asp.net Mvc 3,Asp.net Mvc 4,Asp.net Web Api,我需要从web api控制器获取csv文件。我无法显示“另存为”对话框。页面上只显示文本输出。我尝试了这两种方法,从jquery调用Export,也调用普通的旧html 控制器: [System.Web.Http.HttpGet] public HttpResponseMessage Export() { StringBuilder sb = new StringBuilder(); IEnumerable<CustomerDiscount> list = this.

我需要从web api控制器获取csv文件。我无法显示“另存为”对话框。页面上只显示文本输出。我尝试了这两种方法,从jquery调用Export,也调用普通的旧html

控制器:

[System.Web.Http.HttpGet]
public HttpResponseMessage Export()
{
    StringBuilder sb = new StringBuilder();
    IEnumerable<CustomerDiscount> list = this.subscriberRepository.GetSubscribers();

    foreach (CustomerDiscount item in list)
    {
        sb.AppendFormat(
            "{0};{1};{2};",
            item.CustomerName,
            item.CustomerNumber,
            Environment.NewLine);
    }

    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(sb.ToString());
    writer.Flush();
    stream.Position = 0;

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("text/csv");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
    return result;
}
还是不行

我这样称呼它:

<a id="export" href="/Relay/Billing/Export" class="btn btn-primary">Export</a>
$("#export").click(function () {
    $.post("/Relay/Billing/Export", { type: $("#discountType").val() })
      .done(function (data) {
      });
});

仍然没有“另存为”框

我不知道这是否是正确的协议,但我以前就是这样做的。所以您有一个网页,您将从中调用一个API,该API将与文件一起响应,并且应该由浏览器的“另存为”对话框来处理

HTML:

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

    <script type="text/javascript">
        function save() {
            window.open('http://localhost:45719/api/home?id=12', '_blank', '');
        }
    </script>
</head>
<body>
    <a class="btn btn-primary" onclick="save()">Export</a>
</body>
</html>

这在Chrome和Firefox最新版本中对我都有效。

我有点困惑,可能是重复的。典型的web api或restful服务返回JSON(或某种类型的序列化)。我假设您的消费者不是web浏览器?请尝试在返回结果之前添加此行:
result.Content.Headers.ContentDisposition=new ContentDispositionHeaderValue(“附件”){FileName=“some.csv”}如果您想调用一个返回CSV文件的方法,您最好使用它。Web API用于返回控制器返回内容的数据(通常)。我认为CSV文件(尤其是你调用它的方式)是内容而不是数据。它打开了一个新的浏览器窗口,但不是另存为dialog@ShaneKm您是否检查了您的浏览器设置是否阻止了此操作?因为如上所述,我在Chrome和Firefox中获得了它,就像任何另存为一样。但对网络应用程序来说不是这样,这样做会奏效,但并不合适。请注意,在这种情况下,您将完全写入MemoryStream,而不是响应流。考虑一种情况,你想返回第一百万个素数逗号分隔。实际上,您不需要为所有的响应流分配内存,相反,您应该能够一次一个地将它们写入响应流,并且不需要分配比查找下一个响应流所需的内存更多的内存。这项技术本质上是将流用作单个缓冲区,而不是流。基于@GeorgeMauer所述,此回答中此操作的整个前半部分可以简单地替换为
result.Content=new-StringContent(“你好,世界!”)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script type="text/javascript">
        function save() {
            window.open('http://localhost:45719/api/home?id=12', '_blank', '');
        }
    </script>
</head>
<body>
    <a class="btn btn-primary" onclick="save()">Export</a>
</body>
</html>
public HttpResponseMessage Get(int id)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write("Hello, World!");
    writer.Flush();
    stream.Position = 0;

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
    return result;
}