// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, AgencyContext context) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); var options = new WebpackDevMiddlewareOptions() { HotModuleReplacement = true }; app.UseWebpackDevMiddleware(options); DbInitializer.InitializeDevelop(context); } else { DbInitializer.InitializaProduction(context); } app.UseAuthentication(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc(routes => { routes.Select().Expand().Filter().OrderBy().Count().MaxTop(1000); routes.MapODataServiceRoute("odata", "odata", ModelBuilder.GetEdmModel(app.ApplicationServices)); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}"); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); var options = new WebpackDevMiddlewareOptions() { HotModuleReplacement = true }; app.UseWebpackDevMiddleware(options); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseSignalR(routes => { routes.MapHub <GameLobbyHub>("/gamelobby"); }); app.UseMvc(routes => { routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); }
private void ConfigureDevelopmentFor(IApplicationBuilder app) { var webpackOptions = new WebpackDevMiddlewareOptions { HotModuleReplacement = true, }; // Webpack initialization with hot-reload. app.UseWebpackDevMiddleware(webpackOptions); app.UseDeveloperExceptionPage(); }
public static void UseWebpackDevMiddleware(this IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options = null) { // Validate options if (options == null) { options = new WebpackDevMiddlewareOptions(); } if (options.ReactHotModuleReplacement && !options.HotModuleReplacement) { throw new ArgumentException("To enable ReactHotModuleReplacement, you must also enable HotModuleReplacement."); } // Unlike other consumers of NodeServices, WebpackDevMiddleware dosen't share Node instances, nor does it // use your DI configuration. It's important for WebpackDevMiddleware to have its own private Node instance // because it must *not* restart when files change (if it did, you'd lose all the benefits of Webpack // middleware). And since this is a dev-time-only feature, it doesn't matter if the default transport isn't // as fast as some theoretical future alternative. var appEnv = (IApplicationEnvironment)appBuilder.ApplicationServices.GetService(typeof(IApplicationEnvironment)); var nodeServices = Configuration.CreateNodeServices(new NodeServicesOptions { HostingModel = NodeHostingModel.Http, ProjectPath = appEnv.ApplicationBasePath, WatchFileExtensions = new string[] {} // Don't watch anything }); // Get a filename matching the middleware Node script var script = EmbeddedResourceReader.Read(typeof(WebpackDevMiddleware), "/Content/Node/webpack-dev-middleware.js"); var nodeScript = new StringAsTempFile(script); // Will be cleaned up on process exit // Tell Node to start the server hosting webpack-dev-middleware var devServerOptions = new { webpackConfigPath = Path.Combine(appEnv.ApplicationBasePath, options.ConfigFile ?? DefaultConfigFile), suppliedOptions = options }; var devServerInfo = nodeServices.InvokeExport <WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer", JsonConvert.SerializeObject(devServerOptions)).Result; // Proxy the corresponding requests through ASP.NET and into the Node listener var proxyOptions = new ConditionalProxyMiddlewareOptions(WebpackDevMiddlewareScheme, WebpackDevMiddlewareHostname, devServerInfo.Port.ToString()); appBuilder.UseMiddleware <ConditionalProxyMiddleware>(devServerInfo.PublicPath, proxyOptions); // While it would be nice to proxy the /__webpack_hmr requests too, these return an EventStream, // and the Microsoft.Aspnet.Proxy code doesn't handle that entirely - it throws an exception after // a while. So, just serve a 302 for those. appBuilder.Map(WebpackHotMiddlewareEndpoint, builder => { builder.Use(next => async ctx => { ctx.Response.Redirect($"{ WebpackDevMiddlewareScheme }://{ WebpackDevMiddlewareHostname }:{ devServerInfo.Port.ToString() }{ WebpackHotMiddlewareEndpoint }"); await Task.Yield(); }); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); var options = new WebpackDevMiddlewareOptions(); options.HotModuleReplacement = true; //app.UseWebpackDevMiddleware(options); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseAuthentication(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); // global cors policy app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, MoviesDbContext moviesDbContext) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); var options = new WebpackDevMiddlewareOptions() { HotModuleReplacement = true }; app.UseWebpackDevMiddleware(options); } app.UseStaticFiles(); moviesDbContext.CreateSeedData(); app.UseMvc(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); var options = new WebpackDevMiddlewareOptions() { HotModuleReplacement = true }; app.UseWebpackDevMiddleware(options); } app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { var webpackOptions = new WebpackDevMiddlewareOptions { ConfigFile = "webpack.dev.js", HotModuleReplacement = true, ProjectPath = Path.Combine(env.ContentRootPath, "ClientApp/") }; app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(webpackOptions); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.MapWhen(x => !x.Request.Path.Value.StartsWith("/api"), builder => { builder.UseMvc(routes => { routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, MoviesDbContext moviesDbContext) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); var options = new WebpackDevMiddlewareOptions() { HotModuleReplacement = true }; app.UseWebpackDevMiddleware(options); } app.UseStaticFiles(); moviesDbContext.CreateSeedData(); app.UseMvcWithDefaultRoute(); app.Run(async(context) => { await context.Response.WriteAsync("Hello World!"); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); //todo var wpOptions = new WebpackDevMiddlewareOptions { // Starts inside webpack-dev-server --hot HotModuleReplacement = true, ConfigFile = "Scripts/build/webpack.dev.conf.js", }; // Call UseWebpackDevMiddleware before UseStaticFiles app.UseWebpackDevMiddleware(wpOptions); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); // routes.MapSpaFallbackRoute( // name: "spa-fallback", // defaults: new { controller = "Home", action = "Index" }); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); // Setup WebpackDevMidleware for "Hot module replacement" while debugging var options = new WebpackDevMiddlewareOptions() { HotModuleReplacement = true }; app.UseWebpackDevMiddleware(options); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); // Setup additional routing for SPA routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); }
/// <summary> /// Enables Webpack dev middleware support. This hosts an instance of the Webpack compiler in memory /// in your application so that you can always serve up-to-date Webpack-built resources without having /// to run the compiler manually. Since the Webpack compiler instance is retained in memory, incremental /// compilation is vastly faster that re-running the compiler from scratch. /// /// Incoming requests that match Webpack-built files will be handled by returning the Webpack compiler /// output directly, regardless of files on disk. If compilation is in progress when the request arrives, /// the response will pause until updated compiler output is ready. /// </summary> /// <param name="appBuilder">The <see cref="IApplicationBuilder"/>.</param> /// <param name="options">Options for configuring the Webpack compiler instance.</param> public static void UseWebpackDevMiddleware( this IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options = null) { // Prepare options if (options == null) { options = new WebpackDevMiddlewareOptions(); } // Validate options if (options.ReactHotModuleReplacement && !options.HotModuleReplacement) { throw new ArgumentException( "To enable ReactHotModuleReplacement, you must also enable HotModuleReplacement."); } // Unlike other consumers of NodeServices, WebpackDevMiddleware dosen't share Node instances, nor does it // use your DI configuration. It's important for WebpackDevMiddleware to have its own private Node instance // because it must *not* restart when files change (if it did, you'd lose all the benefits of Webpack // middleware). And since this is a dev-time-only feature, it doesn't matter if the default transport isn't // as fast as some theoretical future alternative. var nodeServicesOptions = new NodeServicesOptions(appBuilder.ApplicationServices); nodeServicesOptions.WatchFileExtensions = new string[] { }; // Don't watch anything if (!string.IsNullOrEmpty(options.ProjectPath)) { nodeServicesOptions.ProjectPath = options.ProjectPath; } if (options.EnvironmentVariables != null) { foreach (var kvp in options.EnvironmentVariables) { nodeServicesOptions.EnvironmentVariables[kvp.Key] = kvp.Value; } } var nodeServices = NodeServicesFactory.CreateNodeServices(nodeServicesOptions); // Get a filename matching the middleware Node script var script = EmbeddedResourceReader.Read(typeof(WebpackDevMiddleware), "/Content/Node/webpack-dev-middleware.js"); var nodeScript = new StringAsTempFile(script, nodeServicesOptions.ApplicationStoppingToken); // Will be cleaned up on process exit // Ideally, this would be relative to the application's PathBase (so it could work in virtual directories) // but it's not clear that such information exists during application startup, as opposed to within the context // of a request. var hmrEndpoint = !string.IsNullOrEmpty(options.HotModuleReplacementEndpoint) ? options.HotModuleReplacementEndpoint : "/__webpack_hmr"; // Matches webpack's built-in default // Tell Node to start the server hosting webpack-dev-middleware var devServerOptions = new { webpackConfigPath = Path.Combine(nodeServicesOptions.ProjectPath, options.ConfigFile ?? DefaultConfigFile), suppliedOptions = options, understandsMultiplePublicPaths = true, hotModuleReplacementEndpointUrl = hmrEndpoint }; var devServerInfo = nodeServices.InvokeExportAsync <WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer", JsonConvert.SerializeObject(devServerOptions, jsonSerializerSettings)).Result; // If we're talking to an older version of aspnet-webpack, it will return only a single PublicPath, // not an array of PublicPaths. Handle that scenario. if (devServerInfo.PublicPaths == null) { devServerInfo.PublicPaths = new[] { devServerInfo.PublicPath }; } // Proxy the corresponding requests through ASP.NET and into the Node listener // Anything under /<publicpath> (e.g., /dist) is proxied as a normal HTTP request with a typical timeout (100s is the default from HttpClient), // plus /__webpack_hmr is proxied with infinite timeout, because it's an EventSource (long-lived request). foreach (var publicPath in devServerInfo.PublicPaths) { appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath + hmrEndpoint, devServerInfo.Port, Timeout.InfiniteTimeSpan); appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath, devServerInfo.Port, TimeSpan.FromSeconds(100)); } }
static INodeServices fallbackNodeServices; // Used only if no INodeServices was registered with DI public static void UseWebpackDevMiddleware(this IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options = null) { // Validate options if (options != null) { if (options.ReactHotModuleReplacement && !options.HotModuleReplacement) { throw new ArgumentException("To enable ReactHotModuleReplacement, you must also enable HotModuleReplacement."); } } // Get the NodeServices instance from DI var nodeServices = (INodeServices)appBuilder.ApplicationServices.GetService(typeof(INodeServices)) ?? fallbackNodeServices; // Consider removing the following. Having it means you can get away with not putting app.AddNodeServices() // in your startup file, but then again it might be confusing that you don't need to. var appEnv = (IApplicationEnvironment)appBuilder.ApplicationServices.GetService(typeof(IApplicationEnvironment)); if (nodeServices == null) { nodeServices = fallbackNodeServices = Configuration.CreateNodeServices(NodeHostingModel.Http, appEnv.ApplicationBasePath); } // Get a filename matching the middleware Node script var script = EmbeddedResourceReader.Read(typeof(WebpackDevMiddleware), "/Content/Node/webpack-dev-middleware.js"); var nodeScript = new StringAsTempFile(script); // Will be cleaned up on process exit // Tell Node to start the server hosting webpack-dev-middleware var devServerOptions = new { webpackConfigPath = Path.Combine(appEnv.ApplicationBasePath, "webpack.config.js"), suppliedOptions = options ?? new WebpackDevMiddlewareOptions() }; var devServerInfo = nodeServices.InvokeExport <WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer", JsonConvert.SerializeObject(devServerOptions)).Result; // Proxy the corresponding requests through ASP.NET and into the Node listener appBuilder.Map(devServerInfo.PublicPath, builder => { builder.RunProxy(new ProxyOptions { Host = WebpackDevMiddlewareHostname, Port = devServerInfo.Port.ToString() }); }); // While it would be nice to proxy the /__webpack_hmr requests too, these return an EventStream, // and the Microsoft.Aspnet.Proxy code doesn't handle that entirely - it throws an exception after // a while. So, just serve a 302 for those. appBuilder.Map(WebpackHotMiddlewareEndpoint, builder => { builder.Use(next => async ctx => { ctx.Response.Redirect($"http://localhost:{ devServerInfo.Port.ToString() }{ WebpackHotMiddlewareEndpoint }"); await Task.Yield(); }); }); }