Skip to content

Instantly share code, notes, and snippets.

@whyleee
Created September 27, 2018 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save whyleee/9e2557e4960765b88ad3b3a8c7e0eb7d to your computer and use it in GitHub Desktop.
Save whyleee/9e2557e4960765b88ad3b3a8c7e0eb7d to your computer and use it in GitHub Desktop.
Inject Webpack output HTML into ASP.NET MVC
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