Is it possible, once a Razor View
has been rendered in the browser, that the HTML and the contents of the mark up (images, tables, data etc.) can be saved as a string or other type?
I want to be able to generate the Razor View
for the customer to check everything is ok in the output, then I want them to click a button that saves all of the HTML (Without all of the razor markup etc.).
How do you pass the HTML back to an Action
, if it has to be processed pre-rendering, then how can this also be done.
I can then use this to generate PDF's and also save time on processing, as I will save the string in a database.
BTW, this is not a partial view nor will it use partial views, also I know there are still some things to fix in the Razor View, I am more interested in the saving the HTML at this point.
TIA
You can use Middleware to obtain a copy of the HTML that is being sent to the browser. Create a class named ResponseToString
with the following content:
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);
}
}
}
Replace the // save the HTML
with some code to persist the HTML as required. Register the Middleware in your Startup's Configure
method early:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseMiddleware<ResponseToStringMidleware>();
...
}
Further infomration: Middleware in Razor Pages
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.