mirror of
https://github.com/aspnet/JavaScriptServices.git
synced 2025-12-23 01:58:29 +00:00
Add example of full-page prerendering via a custom action result
This commit is contained in:
47
samples/misc/Webpack/ActionResults/PrerenderResult.cs
Normal file
47
samples/misc/Webpack/ActionResults/PrerenderResult.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.NodeServices;
|
||||
using Microsoft.AspNetCore.SpaServices.Prerendering;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Webpack.ActionResults
|
||||
{
|
||||
// This is an example of how you could invoke the prerendering API from an ActionResult, so as to
|
||||
// prerender a SPA component as the entire response page (instead of injecting the SPA component
|
||||
// into a Razor view's output)
|
||||
public class PrerenderResult : ActionResult
|
||||
{
|
||||
private JavaScriptModuleExport _moduleExport;
|
||||
private object _dataToSupply;
|
||||
|
||||
public PrerenderResult(JavaScriptModuleExport moduleExport, object dataToSupply = null)
|
||||
{
|
||||
_moduleExport = moduleExport;
|
||||
_dataToSupply = dataToSupply;
|
||||
}
|
||||
|
||||
public override async Task ExecuteResultAsync(ActionContext context)
|
||||
{
|
||||
var nodeServices = context.HttpContext.RequestServices.GetRequiredService<INodeServices>();
|
||||
var hostEnv = context.HttpContext.RequestServices.GetRequiredService<IHostingEnvironment>();
|
||||
var applicationBasePath = hostEnv.ContentRootPath;
|
||||
var request = context.HttpContext.Request;
|
||||
var response = context.HttpContext.Response;
|
||||
|
||||
var prerenderedHtml = await Prerenderer.RenderToString(
|
||||
applicationBasePath,
|
||||
nodeServices,
|
||||
_moduleExport,
|
||||
request.GetEncodedUrl(),
|
||||
request.Path + request.QueryString.Value,
|
||||
_dataToSupply
|
||||
);
|
||||
|
||||
response.ContentType = "text/html";
|
||||
await response.WriteAsync(prerenderedHtml.Html);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.SpaServices.Prerendering;
|
||||
|
||||
namespace Webpack.ActionResults
|
||||
{
|
||||
public static class PrerenderResultExtensions
|
||||
{
|
||||
public static PrerenderResult Prerender(this ControllerBase controller, JavaScriptModuleExport exportToPrerender, object dataToSupply = null)
|
||||
{
|
||||
return new PrerenderResult(exportToPrerender, dataToSupply);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user