X Tutup
Skip to content

Commit 8a5e58a

Browse files
Make WebpackDevMiddleware able to pass the request through to other middleware for files not served by Webpack
1 parent f7bc478 commit 8a5e58a

File tree

4 files changed

+99
-10
lines changed

4 files changed

+99
-10
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
using System;
2+
using System.Linq;
3+
using System.Net;
4+
using System.Net.Http;
5+
using System.Threading.Tasks;
6+
using Microsoft.AspNet.Builder;
7+
using Microsoft.AspNet.Http;
8+
9+
namespace Microsoft.AspNet.SpaServices.Webpack
10+
{
11+
// Based on https://github.com/aspnet/Proxy/blob/dev/src/Microsoft.AspNetCore.Proxy/ProxyMiddleware.cs
12+
// Differs in that, if the proxied request returns a 404, we pass through to the next middleware in the chain
13+
// This is useful for Webpack middleware, because it lets you fall back on prebuilt files on disk for
14+
// chunks not exposed by the current Webpack config (e.g., DLL/vendor chunks).
15+
internal class ConditionalProxyMiddleware {
16+
private RequestDelegate next;
17+
private ConditionalProxyMiddlewareOptions options;
18+
private HttpClient httpClient;
19+
private string pathPrefix;
20+
21+
public ConditionalProxyMiddleware(RequestDelegate next, string pathPrefix, ConditionalProxyMiddlewareOptions options)
22+
{
23+
this.next = next;
24+
this.pathPrefix = pathPrefix;
25+
this.options = options;
26+
this.httpClient = new HttpClient(new HttpClientHandler());
27+
}
28+
29+
public async Task Invoke(HttpContext context)
30+
{
31+
if (context.Request.Path.StartsWithSegments(this.pathPrefix)) {
32+
var didProxyRequest = await PerformProxyRequest(context);
33+
if (didProxyRequest) {
34+
return;
35+
}
36+
}
37+
38+
// Not a request we can proxy
39+
await this.next.Invoke(context);
40+
}
41+
42+
private async Task<bool> PerformProxyRequest(HttpContext context) {
43+
var requestMessage = new HttpRequestMessage();
44+
45+
// Copy the request headers
46+
foreach (var header in context.Request.Headers) {
47+
if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null) {
48+
requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
49+
}
50+
}
51+
52+
requestMessage.Headers.Host = options.Host + ":" + options.Port;
53+
var uriString = $"{options.Scheme}://{options.Host}:{options.Port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
54+
requestMessage.RequestUri = new Uri(uriString);
55+
requestMessage.Method = new HttpMethod(context.Request.Method);
56+
57+
using (var responseMessage = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted)) {
58+
if (responseMessage.StatusCode == HttpStatusCode.NotFound) {
59+
// Let some other middleware handle this
60+
return false;
61+
}
62+
63+
// We can handle this
64+
context.Response.StatusCode = (int)responseMessage.StatusCode;
65+
foreach (var header in responseMessage.Headers) {
66+
context.Response.Headers[header.Key] = header.Value.ToArray();
67+
}
68+
69+
foreach (var header in responseMessage.Content.Headers) {
70+
context.Response.Headers[header.Key] = header.Value.ToArray();
71+
}
72+
73+
// SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
74+
context.Response.Headers.Remove("transfer-encoding");
75+
await responseMessage.Content.CopyToAsync(context.Response.Body);
76+
return true;
77+
}
78+
}
79+
}
80+
81+
internal class ConditionalProxyMiddlewareOptions {
82+
public string Scheme { get; private set; }
83+
public string Host { get; private set; }
84+
public string Port { get; private set; }
85+
86+
public ConditionalProxyMiddlewareOptions(string scheme, string host, string port) {
87+
this.Scheme = scheme;
88+
this.Host = host;
89+
this.Port = port;
90+
}
91+
}
92+
}

src/Microsoft.AspNet.SpaServices/Webpack/WebpackDevMiddleware.cs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
using System.IO;
33
using System.Threading.Tasks;
44
using Microsoft.AspNet.NodeServices;
5-
using Microsoft.AspNet.Proxy;
65
using Microsoft.AspNet.SpaServices.Webpack;
76
using Microsoft.Extensions.PlatformAbstractions;
87
using Newtonsoft.Json;
@@ -12,8 +11,10 @@ namespace Microsoft.AspNet.Builder
1211
{
1312
public static class WebpackDevMiddleware
1413
{
14+
const string WebpackDevMiddlewareScheme = "http";
1515
const string WebpackDevMiddlewareHostname = "localhost";
1616
const string WebpackHotMiddlewareEndpoint = "/__webpack_hmr";
17+
const string DefaultConfigFile = "webpack.config.js";
1718

1819
public static void UseWebpackDevMiddleware(this IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options = null) {
1920
// Validate options
@@ -41,25 +42,21 @@ public static void UseWebpackDevMiddleware(this IApplicationBuilder appBuilder,
4142

4243
// Tell Node to start the server hosting webpack-dev-middleware
4344
var devServerOptions = new {
44-
webpackConfigPath = Path.Combine(appEnv.ApplicationBasePath, "webpack.config.js"),
45+
webpackConfigPath = Path.Combine(appEnv.ApplicationBasePath, options.ConfigFile ?? DefaultConfigFile),
4546
suppliedOptions = options ?? new WebpackDevMiddlewareOptions()
4647
};
4748
var devServerInfo = nodeServices.InvokeExport<WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer", JsonConvert.SerializeObject(devServerOptions)).Result;
4849

4950
// Proxy the corresponding requests through ASP.NET and into the Node listener
50-
appBuilder.Map(devServerInfo.PublicPath, builder => {
51-
builder.RunProxy(new ProxyOptions {
52-
Host = WebpackDevMiddlewareHostname,
53-
Port = devServerInfo.Port.ToString()
54-
});
55-
});
51+
var proxyOptions = new ConditionalProxyMiddlewareOptions(WebpackDevMiddlewareScheme, WebpackDevMiddlewareHostname, devServerInfo.Port.ToString());
52+
appBuilder.UseMiddleware<ConditionalProxyMiddleware>(devServerInfo.PublicPath, proxyOptions);
5653

5754
// While it would be nice to proxy the /__webpack_hmr requests too, these return an EventStream,
5855
// and the Microsoft.Aspnet.Proxy code doesn't handle that entirely - it throws an exception after
5956
// a while. So, just serve a 302 for those.
6057
appBuilder.Map(WebpackHotMiddlewareEndpoint, builder => {
6158
builder.Use(next => async ctx => {
62-
ctx.Response.Redirect($"http://localhost:{ devServerInfo.Port.ToString() }{ WebpackHotMiddlewareEndpoint }");
59+
ctx.Response.Redirect($"{ WebpackDevMiddlewareScheme }://{ WebpackDevMiddlewareHostname }:{ devServerInfo.Port.ToString() }{ WebpackHotMiddlewareEndpoint }");
6360
await Task.Yield();
6461
});
6562
});

src/Microsoft.AspNet.SpaServices/Webpack/WebpackDevMiddlewareOptions.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,6 @@ namespace Microsoft.AspNet.SpaServices.Webpack {
22
public class WebpackDevMiddlewareOptions {
33
public bool HotModuleReplacement { get; set; }
44
public bool ReactHotModuleReplacement { get; set; }
5+
public string ConfigFile { get; set; }
56
}
67
}

src/Microsoft.AspNet.SpaServices/project.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
"dependencies": {
1616
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
1717
"Microsoft.AspNet.Routing": "1.0.0-rc1-final",
18-
"Microsoft.AspNet.Proxy": "1.0.0-rc1-final",
1918
"Microsoft.AspNet.NodeServices": "1.0.0-alpha7"
2019
},
2120
"frameworks": {

0 commit comments

Comments
 (0)
X Tutup