[asp.net-mvc]获取生成的 html 文件内的行动

发布时间: 2016/10/9 6:07:17
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有一个 MVC 控制器,提供了一个简单的视图

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。

解决方法 1:

检查出http://approache.com/blog/render-any-aspnet-mvc-actionresult-to/的这篇文章。它给出了整洁的方式来呈现的任何一个为字符串输出。

编辑

建立在上述文章中概述的技术上,一个完整的解决方案可能看起来像这样

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;
        }
    }
}
赞助商