Save a Rendered Razor View as HTML string
在浏览器中呈现 我希望能够生成 如何将HTML传递回
然后我可以用它来生成PDF,而且还节省了处理时间,因为我会将字符串保存在数据库中。
BTW,这不是局部视图,也不使用局部视图,我也知道还有一些问题需要解决在Razor视图中,我现在对保存HTML更加感兴趣。
TIA
HTML预渲染HTML后期渲染
您可以使用中间件来获取发送到浏览器的HTML的副本。创建一个名为
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); } } } |
用一些代码替换
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页面中的中间件