创建文本文件并下载而不保存在ASP.net Core MVC 2.1中的服务器上 [英] Create text file and download without saving on server in ASP.net Core MVC 2.1

查看:56
本文介绍了创建文本文件并下载而不保存在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");

文件名参数将提示 Content-Disposition:附件;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屋!

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