1
+ using System . Threading . Tasks ;
2
+ using Microsoft . AspNetCore . Hosting ;
3
+ using Microsoft . AspNetCore . Http ;
4
+ using Microsoft . AspNetCore . Http . Extensions ;
5
+ using Microsoft . AspNetCore . Mvc ;
6
+ using Microsoft . AspNetCore . NodeServices ;
7
+ using Microsoft . AspNetCore . SpaServices . Prerendering ;
8
+ using Microsoft . Extensions . DependencyInjection ;
9
+
10
+ namespace Webpack . ActionResults
11
+ {
12
+ // This is an example of how you could invoke the prerendering API from an ActionResult, so as to
13
+ // prerender a SPA component as the entire response page (instead of injecting the SPA component
14
+ // into a Razor view's output)
15
+ public class PrerenderResult : ActionResult
16
+ {
17
+ private JavaScriptModuleExport _moduleExport ;
18
+ private object _dataToSupply ;
19
+
20
+ public PrerenderResult ( JavaScriptModuleExport moduleExport , object dataToSupply = null )
21
+ {
22
+ _moduleExport = moduleExport ;
23
+ _dataToSupply = dataToSupply ;
24
+ }
25
+
26
+ public override async Task ExecuteResultAsync ( ActionContext context )
27
+ {
28
+ var nodeServices = context . HttpContext . RequestServices . GetRequiredService < INodeServices > ( ) ;
29
+ var hostEnv = context . HttpContext . RequestServices . GetRequiredService < IHostingEnvironment > ( ) ;
30
+ var applicationBasePath = hostEnv . ContentRootPath ;
31
+ var request = context . HttpContext . Request ;
32
+ var response = context . HttpContext . Response ;
33
+
34
+ var prerenderedHtml = await Prerenderer . RenderToString (
35
+ applicationBasePath ,
36
+ nodeServices ,
37
+ _moduleExport ,
38
+ request . GetEncodedUrl ( ) ,
39
+ request . Path + request . QueryString . Value ,
40
+ _dataToSupply
41
+ ) ;
42
+
43
+ response . ContentType = "text/html" ;
44
+ await response . WriteAsync ( prerenderedHtml . Html ) ;
45
+ }
46
+ }
47
+ }
0 commit comments