网站 API return csv 文件

Web API return csv file

我需要从网络 api 控制器获取一个 csv 文件。我无法显示 "Save As" 对话框。只有文本输出显示在页面上。我都试过了,从 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;
}

编辑: 添加了这一行:

result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };

还是不行

我这样称呼它:

<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,该文件将响应该文件,它应该由浏览器的另存为对话框处理。

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>

操作:

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;
}

这对我来说在 Chrome 和最新的 Firefox 中都有效。

如果您通过 AJAX 呼叫您的 API,则无法出现下载对话框。要么将其设为常规 link(对于使用 GET 的 API),或者,如果您需要将其设为 POST,则将其设为 post 到新的 [=21] =] 使用带有 target="_blank" 的常规形式。

所以,要么 <a href="/Relay/Billing/Export?type=...">click here</a>,要么

<form method="post" target="_blank" action="/Relay/Billing/Export">
<input id="discountType" name="type"/>
<input type="submit">Export</input>
</form>