gpt4 book ai didi

c# - 在 action 中获取生成的 html 文件

转载 作者:太空狗 更新时间:2023-10-29 23:14:57 27 4
gpt4 key购买 nike

我有一个提供简单 View 的 MVC Controller

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。

最佳答案

查看此帖子 http://approache.com/blog/render-any-aspnet-mvc-actionresult-to/ .它提供了一种将任何 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;
}
}
}

关于c# - 在 action 中获取生成的 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22718312/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com