在 ASP.net Core MVC 2.1 中创建文本文件并下载而不保存在服务器上 [英] Create text file and download without saving on server in ASP.net Core MVC 2.1
问题描述
我找到了一种创建文本文件的方法,然后立即将其下载到浏览器中,而无需在常规 ASP.net 中将其写入服务器:
I've found a way to create a text file then instantly download it in the browser without writing it to the server in regular ASP.net:
接受的答案使用:
using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8)) {
writer.Write("This is the content");
}
我需要在 ASP.net Core 2.1 MVC 中执行此操作 - 虽然不知道 Response.OutputStream 是什么 - 我在 Google 上找不到任何帮助解决此问题的内容,或其他方法.
I need to do this in ASP.net Core 2.1 MVC - though in that doesn't know what Response.OutputStream is - and I can't find anything on Google to help with that, or other ways to do this.
我该怎么做?谢谢.
推荐答案
如果您只处理文本,则根本不需要做任何特别的事情.只需返回一个 ContentResult
:
If you're dealing with just text, you don't need to do anything special at all. Just return a ContentResult
:
return Content("This is some text.", "text/plain");
这对于其他文本"内容类型(如 CSV)也同样适用:
This works the same for other "text" content types, like CSV:
return Content("foo,bar,baz", "text/csv");
如果您想强制下载,您可以使用 FileResult
并简单地传递 byte[]
:
If you're trying to force a download, you can utilize FileResult
and simply pass the byte[]
:
return File(Encoding.UTF8.GetBytes(text), "text/plain", "foo.txt");
filename
参数提示 Content-Disposition:attachment;filename="foo.txt"
标题.或者,您可以返回 Content
并手动设置此标题:
The filename
param prompts a Content-Disposition: attachment; filename="foo.txt"
header. Alternatively, you can return Content
and just set this header manually:
Response.Headers.Add("Content-Disposition", "attachment; filename="foo.txt"");
return Content(text, "text/plain");
最后,如果您在流中构建文本,则只需返回一个 FileStreamResult
:
Finally, if you're building the text in a stream, then simply return a FileStreamResult
:
return File(stream, "text/plain", "foo.txt");
这篇关于在 ASP.net Core MVC 2.1 中创建文本文件并下载而不保存在服务器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!