在ASP.NET MVC中下载动态生成的文件 [英] Download Dynamically Generated File in ASP.NET MVC

查看:68
本文介绍了在ASP.NET MVC中下载动态生成的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在ASP.NET MVC中实现文件下载.在网上搜索,我发现了这样的代码:

I need to implement a file download in ASP.NET MVC. Searching the Web, I found code like this:

public ActionResult GetFile()
{
    return File(filename, "text/csv", Server.UrlEncode(filename));
}

很好,但是我想动态创建该文件的内容.

That's nice, but I want to create the contents of this file dynamically.

我意识到我可以动态创建文件,然后使用上面的语法下载该文件.但是,如果我可以直接将我的内容直接写到响应中,这会不会更有效率?在MVC中有可能吗?

I realize I could dynamically create the file, and then use the syntax above to download that file. But wouldn't it be more efficient if I could simply write my contents directly to the response? Is this possible in MVC?

推荐答案

这是我最终使用的代码的过于简化的版本.满足我的需求.

Here's an overly simplified version of the code I ended up using. It meets my needs.

[HttpGet]
public ActionResult GetFile()
{
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=myfile.csv");
    Response.ContentType = "text/csv";

    // Write all my data
    Response.Write(...);
    Response.End();

    // Not sure what else to do here
    return Content(String.Empty);
}

这篇关于在ASP.NET MVC中下载动态生成的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆