C# 在操作中获取生成的html文件
我有一个MVC控制器,它提供了一个简单的视图C# 在操作中获取生成的html文件,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我有一个MVC控制器,它提供了一个简单的视图 public class MyController : Controller { [HttpGet] public ActionResult Index() { return View(); } [HttpGet] public ActionResult ZipIndex() { // Get the file returned bu Index() and zip it
public class MyController : Controller {
[HttpGet]
public ActionResult Index() {
return View();
}
[HttpGet]
public ActionResult ZipIndex() {
// Get the file returned bu Index() and zip it
return File(/* zip stream */);
}
}
从上面可以看出,我需要实现的是一个方法,该方法获取Index()生成的html,将其压缩并作为可下载的文件返回
我知道如何压缩,但我不知道如何获取html。查看此帖子。它提供了一种将任何ActionResult的输出呈现为字符串的简洁方法
编辑
基于上述文章中概述的技术,完整的解决方案可能如下所示
using System.IO;
using System.IO.Compression;
using System.Web;
public class MyController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpGet]
public FileContentResult ZipIndex()
{
// Render the View output:
var viewString = View("TheViewToRender").Capture(ControllerContext);
// Create a zip file containing the resulting markup
using (MemoryStream outputStream = new MemoryStream())
{
StreamReader sr = new StringReader(viewString);
using (ZipArchive zip = new ZipArchive(outputStream, ZipArchiveMode.Create, false))
{
ZipArchiveEntry entry = zip.CreateEntry("MyView.html", CompressionLevel.Optimal);
using (var entryStream = entry.Open())
{
sr.BaseStream.CopyTo(entryStream);
}
}
return File(outputStream.ToArray(), MediaTypeNames.Application.Zip, "Filename.zip");
}
}
}
public static class ActionResultExtensions {
public static string Capture(this ActionResult result, ControllerContext controllerContext) {
using (var it = new ResponseCapture(controllerContext.RequestContext.HttpContext.Response)) {
result.ExecuteResult(controllerContext);
return it.ToString();
}
}
}
public class ResponseCapture : IDisposable {
private readonly HttpResponseBase response;
private readonly TextWriter originalWriter;
private StringWriter localWriter;
public ResponseCapture(HttpResponseBase response) {
this.response = response;
originalWriter = response.Output;
localWriter = new StringWriter();
response.Output = localWriter;
}
public override string ToString() {
localWriter.Flush();
return localWriter.ToString();
}
public void Dispose() {
if (localWriter != null) {
localWriter.Dispose();
localWriter = null;
response.Output = originalWriter;
}
}
}
签出-可能是答案。如果用户需要页面的HTML内容,难道他们不能右键单击并另存为吗?@RichardEverett如果许多用户真的知道可以保存页面的源代码(并且有方便的方法-例如在手机上),我会感到惊讶。请注意,结果可能不是HTML(即CSV)-因此,对于同一视图的查看和下载zip,有一种简单的方法对我来说非常合理。@AlexeiLevenkov。谢谢。这很有效。我想知道是否有办法直接调用Index()方法?链接到的方法需要将模型作为参数。我在Index()中有很多代码来设置视图,不想在ZipIndex()中复制它。@IlirDeda我已经扩展了下面的回复,以展示一个使用视图渲染和.NET 4.5 zip技术的解决方案。这似乎只有在现在使用模型的情况下才起作用。当我使用模型时,它无法填充它。