今天看到一位高人写的一篇讲述ASP .NET Core 的运行机制和启动的文章,非常好,部分内容转一下。
ASP.NET Core 的启动和运行机制 - 车骑 - 博客园 (cnblogs.com)https://www.cnblogs.com/royzshare/p/9442666.html#asp-net-core-%E7%9A%84%E5%90%AF%E5%8A%A8
目录
一、ASP .NET Core 的运行机制
二、ASP .NET Core 的启动
一、ASP .NET Core 的运行机制
- Web Server: ASP.NET Core 提供两种服务器可用, 分别是 Kestrel 和 HTTP.sys (Core 1.x 中被命名为 WebListener),
- Kestrel是一个跨平台的Web服务器。
- HTTP.sys只能用在Windows系统中.
- Internet: 当需要部署在Internal Network 中并需要 Kestrel 中没有的功能(如 Windows 身份验证)时,可以选择HTTP.sys。
- IIS、Apache、Nginx: Kestrel 可以单独使用 ,也可以将其与反向代理服务器(如 IIS、Nginx 或 Apache)结合使用。 请求经这些服务器进行初步处理后转发给Kestrel(即图中虚线的可选流程).
二、ASP .NET Core 的启动
Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup()
.Build();
}
- Main: 程序的起点. ASP .NET Core 应用程序本质上是控制台应用程序。
- CreateDefaultBuilder:创建并配置WebHostBuilder, 首先调用CreateDefaultBuilder( 如图所示, 它是一系列配置的大综合,下文做详细介绍), 进行一系列配置。
- UseStartup: 指定Startup为启动配置文件. 在Startup中, 将进行两个比较重要的工作, 服务的依赖注入和配置管道。
- ConfigureServices方法是注册服务
- Configure方法是配置管道,用来具体指定如何处理每个http请求的, 例如我们可以让这个程序知道我使用mvc来处理http请求, 那就调用app.UseMvc()这个方法就行.
- BuildWebHost:生成WebHostBuilder并进行了一系列配置之后, 通过这个WebHostBuilder来Build出一个IWebHost。
- Run:调用IWebHost的Run方法使之开始运行。
CreateDefaultBuilder
public static IWebHostBuilder CreateDefaultBuilder(string[] args)
{
var builder = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
if (env.IsDevelopment())
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseIISIntegration()
.UseDefaultServiceProvider((context, options) =>
{
options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
});
return builder;
}
- UseKestrel 指定服务器使用 Kestrel,若使用HttpSys,需使用UseHttpSys。
- UseContentRoot 指定根目录
- ConfigureAppConfiguration 读取配置文件
- ConfigureLogging 配置日志处理程序
- UseIISIntegration 将应用程序配置为在 IIS 中运行。如果应用程序没有使用 IIS 作为反向代理,那么 UseIISIntegration 不会有任何效果。因此,即使应用程序在非 IIS 方案中运行,也可以安全调用这种方法。
- UseDefaultServiceProvider 设置默认的依赖注入容器。
=========================================================================
另一位高人的几个图也收藏一下:
ASP.NET Core MVC 源码学习:MVC 启动流程详解 - Savorboard - 博客园 (cnblogs.com)https://www.cnblogs.com/savorboard/p/aspnetcore-mvc-startup.html



