asp.net core mvc 中间件之WebpackDevMiddleware

本文涉及的产品
Serverless 应用引擎 SAE,800核*时 1600GiB*时
云原生网关 MSE Higress,422元/月
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介: asp.net core mvc 中间件之WebpackDevMiddlewareWebpackDevMiddleware中间件主要用于开发SPA应用,启用Webpack,增强网页开发体验。好吧,你想用来干嘛就干嘛,这次主要是通过学习该中间件,学习如何在core中启用Webpack支持通过上上篇asp.

asp.net core mvc 中间件之WebpackDevMiddleware

  • WebpackDevMiddleware中间件主要用于开发SPA应用,启用Webpack,增强网页开发体验。好吧,你想用来干嘛就干嘛,这次主要是通过学习该中间件,学习如何在core中启用Webpack支持
  • 通过上上篇asp.net core mvc 管道之中间件,大致可以了解中间件是什么东西,现在就以中间件为单位,一个一个点学习各种中间件,了解并掌握,最后学会自己写中间件
  • 该中间件源码

说明

WebpackDevMiddleware

  • 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.

  • 大概意思是Webpack编译器实例存在于内存,始终提供最新编译的资源,增量编译比重新编译速度要快得多。任何请求Webpack编译后的文件,都原样返回,如果请求到达时编译没完成,响应将暂停,直到编译完成,输出准备就绪

NodeServices

  • 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.

  • WebpackDevMiddleware不共享Node实例,也不共享使用的DI配置。因为文件改变时Node服务不能重启。这是个开发时使用的功能,所以传输速度可能不会很快

分析

  • 创建Node实例
var nodeServicesOptions = new NodeServicesOptions(appBuilder.ApplicationServices);
var nodeServices = NodeServicesFactory.CreateNodeServices(nodeServicesOptions);
  • 创建devServerOptions,包含设置webpack.config.js的路径以及整合在Stratup.cs的设置、模块热加载断点等。这些设置需要传到Nodeaspnet-webpack模块,如果是自定义的模块,那么参数也是自己定义啦
var devServerOptions = new
{
    webpackConfigPath = Path.Combine(nodeServicesOptions.ProjectPath, options.ConfigFile ?? DefaultConfigFile),
    suppliedOptions = options,
    understandsMultiplePublicPaths = true,
    hotModuleReplacementEndpointUrl = hmrEndpoint
};
  • 下面是通过nodeServices,执行指定aspnet-webpack模块里面的方法并得到结果。参数分别是模块文件路径、要调用的方法、传递的参数。传递给js模块的参数先序列成json字符串,模块接收参数后再反序列化成对象
var devServerInfo =
    nodeServices.InvokeExportAsync<WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer",
        JsonConvert.SerializeObject(devServerOptions, jsonSerializerSettings)).Result;
  • 返回结果是Webpack编译之后的输出目录,循环输出目录,添加请求代理,代理到所有输出目录。超时时间100s, /__webpack_hmr无限超时
  • 代理源码
foreach (var publicPath in devServerInfo.PublicPaths)
{
    appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath + hmrEndpoint, devServerInfo.Port, Timeout.InfiniteTimeSpan);
    appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath, devServerInfo.Port, TimeSpan.FromSeconds(100));
}

// Note that this is hardcoded to make requests to "localhost" regardless of the hostname of the
// server as far as the client is concerned. This is because ConditionalProxyMiddlewareOptions is
// the one making the internal HTTP requests, and it's going to be to some port on this machine
// because aspnet-webpack hosts the dev server there. We can't use the hostname that the client
// sees, because that could be anything (e.g., some upstream load balancer) and we might not be
// able to make outbound requests to it from here.
// Also note that the webpack HMR service always uses HTTP, even if your app server uses HTTPS,
// because the HMR service has no need for HTTPS (the client doesn't see it directly - all traffic
// to it is proxied), and the HMR service couldn't use HTTPS anyway (in general it wouldn't have
// the necessary certificate).
var proxyOptions = new ConditionalProxyMiddlewareOptions(
    "http", "localhost", proxyToPort.ToString(), requestTimeout);
appBuilder.UseMiddleware<ConditionalProxyMiddleware>(publicPath, proxyOptions);

结果

  • 创建自己的中间件,自定义配置,运行Webpack服务,只需要创建Node实例,调用自己写的模块即可。模块根据传过来的配置运行服务即可
  • 关键方法
var nodeServicesOptions = new NodeServicesOptions(appBuilder.ApplicationServices); // node配置

var nodeServices = NodeServicesFactory.CreateNodeServices(nodeServicesOptions); // 创建node实例 

// dev服务配置
var devServerOptions = new
{
    webpackConfigPath = Path.Combine(nodeServicesOptions.ProjectPath, options.ConfigFile ?? DefaultConfigFile),
    suppliedOptions = options,
    understandsMultiplePublicPaths = true,
    hotModuleReplacementEndpointUrl = hmrEndpoint
};

// 调用js模块,运行dev服务,返回输出目录
var devServerInfo =
    nodeServices.InvokeExportAsync<WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer",
        JsonConvert.SerializeObject(devServerOptions, jsonSerializerSettings)).Result;

// 添加输出目录到代理
foreach (var publicPath in devServerInfo.PublicPaths)
{
    appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath + hmrEndpoint, devServerInfo.Port, Timeout.InfiniteTimeSpan);
    appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath, devServerInfo.Port, TimeSpan.FromSeconds(100));
}

private static void UseProxyToLocalWebpackDevMiddleware(this IApplicationBuilder appBuilder, string publicPath, int proxyToPort, TimeSpan requestTimeout)
{
    var proxyOptions = new ConditionalProxyMiddlewareOptions(
        "http", "localhost", proxyToPort.ToString(), requestTimeout);
    appBuilder.UseMiddleware<ConditionalProxyMiddleware>(publicPath, proxyOptions);
}

示例

  • 待更新...
用心做好每一件事,结果会给你最大的惊喜!
目录
相关文章
|
3天前
|
开发框架 监控 .NET
开发者的革新利器:ASP.NET Core实战指南,构建未来Web应用的高效之道
【8月更文挑战第28天】本文探讨了如何利用ASP.NET Core构建高效、可扩展的Web应用。ASP.NET Core是一个开源、跨平台的框架,具有依赖注入、配置管理等特性。文章详细介绍了项目结构规划、依赖注入配置、中间件使用及性能优化方法,并讨论了安全性、可扩展性以及容器化的重要性。通过这些技术要点,开发者能够快速构建出符合现代Web应用需求的应用程序。
11 0
|
3天前
|
缓存 数据库连接 API
Entity Framework Core——.NET 领域的 ORM 利器,深度剖析其最佳实践之路
【8月更文挑战第28天】在软件开发领域,高效的数据访问与管理至关重要。Entity Framework Core(EF Core)作为一款强大的对象关系映射(ORM)工具,在 .NET 开发中扮演着重要角色。本文通过在线书店应用案例,展示了 EF Core 的核心特性和优势。我们定义了 `Book` 实体类及其属性,并通过 `BookStoreContext` 数据库上下文配置了数据库连接。EF Core 提供了简洁的 API,支持数据的查询、插入、更新和删除操作。
14 0
|
7天前
|
开发框架 监控 .NET
【Azure 应用程序见解】在Docker中运行的ASP.NET Core应用如何开启Application Insights的Profiler Trace呢?
【Azure 应用程序见解】在Docker中运行的ASP.NET Core应用如何开启Application Insights的Profiler Trace呢?
|
7天前
|
Linux C# C++
【Azure App Service For Container】创建ASP.NET Core Blazor项目并打包为Linux镜像发布到Azure应用服务
【Azure App Service For Container】创建ASP.NET Core Blazor项目并打包为Linux镜像发布到Azure应用服务
|
16天前
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
26 0
|
16天前
|
开发框架 前端开发 安全
ASP.NET MVC 如何使用 Form Authentication?
ASP.NET MVC 如何使用 Form Authentication?
|
20天前
|
开发框架 .NET
Asp.Net Core 使用X.PagedList.Mvc.Core分页 & 搜索
Asp.Net Core 使用X.PagedList.Mvc.Core分页 & 搜索
72 0
|
4月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
137 0
|
4月前
|
开发框架 前端开发 JavaScript
JavaScript云LIS系统源码ASP.NET CORE 3.1 MVC + SQLserver + Redis医院实验室信息系统源码 医院云LIS系统源码
实验室信息系统(Laboratory Information System,缩写LIS)是一类用来处理实验室过程信息的软件,云LIS系统围绕临床,云LIS系统将与云HIS系统建立起高度的业务整合,以体现“以病人为中心”的设计理念,优化就诊流程,方便患者就医。
62 0
|
4月前
|
开发框架 前端开发 .NET
C# .NET面试系列六:ASP.NET MVC
<h2>ASP.NET MVC #### 1. MVC 中的 TempData\ViewBag\ViewData 区别? 在ASP.NET MVC中,TempData、ViewBag 和 ViewData 都是用于在控制器和视图之间传递数据的机制,但它们有一些区别。 <b>TempData:</b> 1、生命周期 ```c# TempData 的生命周期是短暂的,数据只在当前请求和下一次请求之间有效。一旦数据被读取,它就会被标记为已读,下一次请求时就会被清除。 ``` 2、用途 ```c# 主要用于在两个动作之间传递数据,例如在一个动作中设置 TempData,然后在重定向到另
234 5
下一篇
云函数