ASP.NET Core 7 源码阅读4:MVC核心中间件
2023-06-26 16:24:03摘要:一、核心流程概述 执行AddMVC() 将MVC的核心服务注册到容器,且通过反射扫描把相关dll收集起来 执行app.UseRouting() 将EndpointRoutingMiddleware中间件注册到http管道 执行app. MapControllerRoute() 将本程序集定义的所有Controller-Action-ParameterConversion转换为一个个的ControllerActionDescriptor放到路由中间件的配置对象RouteOptions中,注册并传入EndpointMiddleware中间件注册到http管道中 请求来了,管道模型Build---没啥动作,倒序执行中间件的实例化 收到一条http请求,先进入EndpointRoutingMiddleware,首次请求时会完成ControllerActionDescriptor到EndPoint的转化,然后通过DFA算法匹配一个Endpoint,并放到HttpContext中去 鉴权/授权/其他中间件可以根据根据Endpoint的信息对这个请求进行鉴权授权或其他操作。 EndpointMiddleware中间件执行Endpoint中的RequestDelegate逻辑,即执行FilterController-Action-Result等系列操作(MVC) 二、AddMVC 1. 上帝视角 AddMVC(AddControllersWithViews)是最初发生的,是IOC注册环节的事儿,在管道注册之前,其职责有2个: 添加MVC各种IOC注册,超多。。 反射遍历相关程序集,封装成ApplicationPart,供后续使用 2. 源码解读 从MvcServiceCollectionExtensions开始,绕一圈,最终是AddMvcCore()方法 先实例化ApplicationPartManager-----拿着项目名字,通过反射加载Dll,将信息封装到ApplciationPartManager的ApplicationParts属性中---扩展点 ConfigureDefaultFeatureProviders(partManager);的调用,这行代码是创建了一个新的ControllerFeatureProvide…… 阅读全文