asp.net-mvc – Web API返回csv文件

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – Web API返回csv文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要从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;
}

编辑:
添加了这一行:

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.

猜你在找的asp.Net相关文章