nii*_*ico 4 c# asp.net-core-mvc asp.net-core-2.0 asp.net-core-2.1
我找到了一种创建文本文件,然后立即在浏览器中下载而不将其写入常规ASP.net中的服务器的方法:
接受的答案使用:
using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8)) {
writer.Write("This is the content");
}
Run Code Online (Sandbox Code Playgroud)
我需要在ASP.net Core 2.1 MVC中执行此操作-尽管该操作不知道什么是Response.OutputStream-并且我在Google上找不到任何可用于此目的的方法或其他方法。
我怎样才能做到这一点?谢谢。
在下面的代码中,您使用 Response.OutputStream。但这实际上在 asp.net 中有效,但 Response.OutputStream 在 asp.net 核心中抛出错误。
using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8)) {
writer.Write("This is the content");
}
Run Code Online (Sandbox Code Playgroud)
因此,请使用以下代码在 asp.net core 中下载文件。
using (MemoryStream stream = new MemoryStream())
{
StreamWriter objstreamwriter = new StreamWriter(stream);
objstreamwriter.Write("This is the content");
objstreamwriter.Flush();
objstreamwriter.Close();
return File(stream.ToArray(), "text/plain", "file.txt");
}
Run Code Online (Sandbox Code Playgroud)
如果您只处理文本,则根本不需要做任何特殊的事情。只需返回一个ContentResult:
return Content("This is some text.", "text/plain");
Run Code Online (Sandbox Code Playgroud)
这对于其他“文本”内容类型(例如CSV)也是如此:
return Content("foo,bar,baz", "text/csv");
Run Code Online (Sandbox Code Playgroud)
如果您要强制进行下载,则可以利用FileResult并简单地传递byte[]:
return File(Encoding.UTF8.GetBytes(text), "text/plain", "foo.txt");
Run Code Online (Sandbox Code Playgroud)
所述filenamePARAM提示一个Content-Disposition: attachment; filename="foo.txt"报头。或者,您可以返回Content并仅手动设置此标头:
Response.Headers.Add("Content-Disposition", "attachment; filename=\"foo.txt\"");
return Content(text, "text/plain");
Run Code Online (Sandbox Code Playgroud)
最后,如果您要在流中构建文本,则只需返回FileStreamResult:
return File(stream, "text/plain", "foo.txt");
Run Code Online (Sandbox Code Playgroud)