asp.net-mvc ASP.NET MVC:返回纯文本文件以从控制器方法下载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1569532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC: returning plaintext file to download from controller method
提问by p.campbell
Consider the need to return a plain-text file from a controller method back to the caller. The idea is to have the file downloaded, rather than viewed as plaintext in the browser.
考虑需要从控制器方法返回一个纯文本文件给调用者。这个想法是下载文件,而不是在浏览器中以纯文本形式查看。
I have the following method, and it works as expected. The file is presented to the browser for download, and the file is populated with the string.
我有以下方法,它按预期工作。该文件将呈现给浏览器以供下载,并使用字符串填充该文件。
I'd like to look for a 'more correct' implementation of this method, as I am not 100% comfortable with the voidreturn type.
我想寻找此方法的“更正确”的实现,因为我对void返回类型不是 100% 满意。
public void ViewHL7(int id)
{
string someLongTextForDownload = "ABC123";
Response.Clear();
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.hl7", id.ToString()));
Response.Write(someLongTextForDownload);
Response.End();
}
回答by tvanfosson
Use the File method on the controller class to return a FileResult
使用控制器类上的 File 方法返回 FileResult
public ActionResult ViewHL7( int id )
{
...
return File( Encoding.UTF8.GetBytes( someLongTextForDownLoad ),
"text/plain",
string.Format( "{0}.hl7", id ) );
}
回答by Chris Missal
You'll want to return a FileContentResultfrom your method.
你会想要FileContentResult从你的方法中返回 a 。

