关于c#:将渲染的Razor视图另存为HTML字符串

Save a Rendered Razor View as HTML string

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

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

如何将HTML传递回Action,如果必须在渲染前对其进行处理,那么如何也可以做到这一点。

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

BTW,这不是局部视图,也不使用局部视图,我也知道还有一些问题需要解决在Razor视图中,我现在对保存HTML更加感兴趣。

TIA

HTML预渲染HTML后期渲染


您可以使用中间件来获取发送到浏览器的HTML的副本。创建一个名为ResponseToString的类,其内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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方法中注册中间件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    app.UseMiddleware<ResponseToStringMidleware>();
    ...
}

更多信息:Razor页面中的中间件