Inject Webpack output HTML into ASP.NET MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Configuration; | |
using System.Linq; | |
using System.Net.Http; | |
using System.Text.RegularExpressions; | |
using System.Threading.Tasks; | |
using System.Web.Hosting; | |
using System.Web.Mvc; | |
namespace TestWp.Controllers | |
{ | |
public class WebpackController : Controller | |
{ | |
[ChildActionOnly] | |
public ActionResult Head() | |
{ | |
var html = GetWebpackHtml("head"); | |
return Content(html); | |
} | |
[ChildActionOnly] | |
public ActionResult Body() | |
{ | |
var html = GetWebpackHtml("body"); | |
return Content(html); | |
} | |
private string GetWebpackHtml(string tag) | |
{ | |
var webpackDevServerUrl = ConfigurationManager.AppSettings["WebpackDevServer"]; | |
string html; | |
if (!string.IsNullOrEmpty(webpackDevServerUrl)) | |
{ | |
html = GetHttpString($"{webpackDevServerUrl}/index.html"); | |
} | |
else | |
{ | |
html = System.IO.File.ReadAllText(HostingEnvironment.MapPath("~/static/index.html")); | |
} | |
var match = Regex.Match(html, $"<{tag}>(.*)</{tag}>", RegexOptions.Singleline); | |
var innerHtml = match.Groups[1].Value; | |
return innerHtml; | |
} | |
private string GetHttpString(string url) | |
{ | |
var http = new HttpClient(); | |
try | |
{ | |
return Task.Run(async () => await http.GetStringAsync(url)).GetAwaiter().GetResult(); | |
} | |
catch (HttpRequestException ex) | |
{ | |
var error = (Exception) ex; | |
while (error.InnerException != null) | |
{ | |
error = error.InnerException; | |
} | |
throw new InvalidOperationException("Webpack dev server is not started. Run `yarn serve` in ClientApp directory. Error: " + error.Message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment