将渲染的 Razor 视图另存为 HTML 字符串

Save a Rendered Razor View as HTML string

在浏览器中呈现 Razor View 后,是否可以将 HTML 和标记内容(图像、表格、数据等)另存为字符串还是其他类型?

我希望能够为客户生成 Razor View 以检查输出中的一切是否正常,然后我希望他们单击​​一个按钮来保存所有 HTML(没有所有剃刀标记等)。

如何将 HTML 传回 Action,如果它必须进行预渲染处理,那么如何也可以做到。

然后我可以使用它来生成 PDF 并节省处理时间,因为我会将字符串保存在数据库中。

顺便说一句,这不是局部视图,也不会使用局部视图,而且我知道 Razor 视图中还有一些问题需要修复,我更感兴趣的是在此处保存 HTML点.

TIA

HTML Pre rendering HTML Post Rendering

您可以使用中间件获取发送到浏览器的 HTML 的副本。使用以下内容创建名为 ResponseToString 的 class:

public class ResponseToStringMidleware
{
    RequestDelegate _next;

    public ResponseToStringMidleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var isHtml = context.Response.ContentType?.ToLower().Contains("text/html");
        Stream responseBody = context.Response.Body;
        using (var memoryStream = new MemoryStream())
        {
            context.Response.Body = memoryStream;

            await _next(context);

            if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault())
            {
                memoryStream.Position = 0;
                string html = new StreamReader(memoryStream).ReadToEnd();
                // save the HTML

            }
            memoryStream.Position = 0;
            await memoryStream.CopyToAsync(responseBody);
        }
    }
}

用一些代码替换 // save the HTML 以根据需要保留 HTML。尽早在 Startup 的 Configure 方法中注册中间件:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    app.UseMiddleware<ResponseToStringMidleware>();
    ...
}

更多信息:Middleware in Razor Pages