ASP.NET Core 是微软推出的一种全新的跨平台开源 .NET 框架,用于在 Windows、Mac 或 Linux 上生成基于云的新式 Web 应用程序。国内目前关于Asp.Net Core的书比较少,自己靠着阅读微软官方文档,源码和在52ABP梁老师的教程中慢慢的在一点点的积累Asp.Net Core的知识。因此希望将自己的学习记录下来,以此巩固和交流。

  闲话不多说,我们知道学习一门新的技术,最好的方法就是从它的启动入口进行跟踪,那么接下来我们先来看下Asp.Net Core的入口文件Program.cs。

  笔者使用的.Net SDK 是 2.2版本,所以下面的介绍都是基于2.2版本的。

    public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
} public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}

  我们看到Program中Main函数很像我们之前的Console应用程序,那么它当中的CreateWebHostBuilder究竟做了什么事情呢?既然.Net Core是开源的,我们看源码就方便了很多,接下来就从源码来了解下它究竟做了什么工作。

     /// <summary>
/// Initializes a new instance of the <see cref="WebHostBuilder"/> class with pre-configured defaults.
/// </summary>
/// <remarks>
/// The following defaults are applied to the returned <see cref="WebHostBuilder"/>:
/// use Kestrel as the web server and configure it using the application's configuration providers,
/// set the <see cref="IHostingEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/>,
/// load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostingEnvironment.EnvironmentName"/>].json',
/// load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
/// load <see cref="IConfiguration"/> from environment variables,
/// load <see cref="IConfiguration"/> from supplied command line args,
/// configure the <see cref="ILoggerFactory"/> to log to the console and debug output,
/// and enable IIS integration.
/// </remarks>
/// <param name="args">The command line args.</param>
/// <returns>The initialized <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder CreateDefaultBuilder(string[] args)
{
var builder = new WebHostBuilder(); if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
{
builder.UseContentRoot(Directory.GetCurrentDirectory());
}
if (args != null)
{
builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
} builder.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();
logging.AddEventSourceLogger();
}).
UseDefaultServiceProvider((context, options) =>
{
options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
}); ConfigureWebDefaults(builder); return builder;
}
 internal static void ConfigureWebDefaults(IWebHostBuilder builder)
{
builder.UseKestrel((builderContext, options) =>
{
options.Configure(builderContext.Configuration.GetSection("Kestrel"));
})
.ConfigureServices((hostingContext, services) =>
{
// Fallback
services.PostConfigure<HostFilteringOptions>(options =>
{
if (options.AllowedHosts == null || options.AllowedHosts.Count == )
{
// "AllowedHosts": "localhost;127.0.0.1;[::1]"
var hosts = hostingContext.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
// Fall back to "*" to disable.
options.AllowedHosts = (hosts?.Length > ? hosts : new[] { "*" });
}
});
// Change notification
services.AddSingleton<IOptionsChangeTokenSource<HostFilteringOptions>>(
new ConfigurationChangeTokenSource<HostFilteringOptions>(hostingContext.Configuration)); services.AddTransient<IStartupFilter, HostFilteringStartupFilter>(); services.AddRouting();
})
.UseIIS()
.UseIISIntegration();
}

  从源码中我们可以看到,CreateDefaultBuilder执行的任务有:

  1、加载主机和应用程序的配置表信息

  2、配置日志记录

  3、设置Web服务器

  4、设置Asp.Net Core应用程序的托管形式。

  现在我们来看一下Asp.Net Core是如何加载配置的。

  访问配置信息可以通过 IConfiguration 接口进行访问,我们从源码也可以看到,Asp.Net Core加载配置的过程,它们之间是按照顺序如果有相同的配置会依次被覆盖:appsettings.json,appsettings{Environment}.json(应用程序配置文件) -->User Secrets(用户机密) --> Environment Variables(环境变量) --> Command-line arguments(命令行参数)。

  其中应用程序配置文件的{Environment}可以在项目的属性中调试进行配置,如果项目中不存在单独为某个环境配置的,采用appsettings.json。

  应用程序配置文件我们比较清楚,以前在.Net Framework我们有web.config,但是Asp.Net Core中出现了User Secrets用户机密,那么它有什么用呢,其实它可以保存我们比较敏感的配置信息,比如第三方的Key,像微信的Appkey之类的。那我们该如何添加User Secrets呢?我们需要在命令行的窗口下,切换到我们项目的执行文件夹下,即bin所在的那层目录,运行命令dotnet user-secrets set [KeyName] [KeyValue]

  接着我们就可以在VS项目中查看到该用户机密了

  

  Environment variables(环境变量)在 Properties文件夹下的launchSettings.json进行配置

{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:4084",
"sslPort":
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"StudentManagement": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

  这里的profiles可以在VS调试运行的时候做选择

  而Command-line arguments(命令行参数)需要结合命令行窗口执行: dotnet run KeyName="KeyValue"。

  那么我们怎么获取配置信息呢? Asp.Net Core提供了ConfigureAppConfiguration 可以给我们调用获取配置,在StartUp文件中可以使用 _configuration["KeyName"] 来获取。

  最后,我们再看一下Asp.Net Core应用程序的托管形式,它有两种托管形式:进程内托管InProcess和进程外托管OutOfProcess。我们知道Asp.Net Core是可以自托管的,它默认托管形式就是InProcess。那么这两种方式的区别是什么呢?

  InProcess:配置进程内托管在项目.csproj文件中 <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>,在InProcess托管情况下,CreateDefaultBuilder()方法调用UseIIS()方法并在IIS工作进程(w3wp.exe或iisexpress.exe)内托管应用程序,从性能角度,InProcess托管比OutOfProcess托管提供了更高的请求吞吐量。

  OutOfProcess:有2个Web服务器-内部Web服务器和外部Web服务器,内部Web服务器是Kestrel,托管进程是dotnet.exe;外部web服务器可以是iis,nginx,apache。

  现在我们知道了CreateDefaultBuilder做了什么工作了,那么在它之后调用了UseStartup<Startup>(),那Startup做了什么工作呢,我们下篇再来讨论。

  

Asp.Net Core 入门(一)——Program.cs做了什么的更多相关文章

  1. CentOS开发ASP.NET Core入门教程

    作者:依乐祝 原文地址:https://www.cnblogs.com/yilezhu/p/9891346.html 因为之前一直没怎么玩过CentOS,大多数时间都是使用Win10进行开发,然后程序 ...

  2. ASP.NET Core 入门教程 10、ASP.NET Core 日志记录(NLog)入门

    一.前言 1.本教程主要内容 ASP.NET Core + 内置日志组件记录控制台日志 ASP.NET Core + NLog 按天记录本地日志 ASP.NET Core + NLog 将日志按自定义 ...

  3. ASP.NET Core入门(一)

    大家好,很荣幸您点了开此篇文章,和我一起来学习ASP.NET Core,此篇文字为<ASP.NET Core入门>系列中的第一篇,本系列将以一个博客系统为例,从第一行代码,到系统发布上线( ...

  4. ASP.NET CORE 入门教程(附源码)

    ASP.NET CORE 入门教程 第一课 基本概念 基本概念 Asp.Net Core Mvc是.NET Core平台下的一种Web应用开发框架 符合Web应用特点 .NET Core跨平台解决方案 ...

  5. 【翻译】ASP.NET Core 入门

    ASP.NET Core 入门 原文地址:Introduction to ASP.NET Core         译文地址:asp.net core 简介           翻译:ganqiyin ...

  6. Asp.Net Core 入门(二)——Startup.cs做了什么

    上篇介绍了Program.cs中Main做了什么,这篇我们来讨论下Startup.cs它又做了什么呢? 我们新建一个Asp.Net Core Mvc项目,先来开一下Startup的代码 public ...

  7. Asp.net Core 入门实战

    Asp.Net Core 是开源,跨平台,模块化,快速而简单的Web框架. Asp.net Core官网的一个合集,方便一次性Clone 目录 快速入门 安装 一个最小的应用 项目模板 路由 静态文件 ...

  8. ASP.NET Core入门

    一.搭建开发环境 在Windows平台下,开发.NET Core 程序需要安装如下内容: 1. .NET Core runtime 2. Visual Studio 2015 with Update ...

  9. ASP.NET Core 入门教程 1、使用ASP.NET Core 构建第一个Web应用

    一.前言 1.本文主要内容 Visual Studio Code 开发环境配置 使用 ASP.NET Core 构建Web应用 ASP.NET Core Web 应用启动类说明 ASP.NET Cor ...

随机推荐

  1. JAVA 布局控制

    在Java里该方法是安一个组件到一个窗体中去,它不同我们使用过的其它GUI系统.首先,它是全代码的:没有控制安放组件的“资源”.其次,该方法的组件被安放到一个被“布局管理器”控制的窗体中,由“布局管理 ...

  2. Code:NFine框架

    ylbtech-Code:NFine框架 1.返回顶部 1.         2. 2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部     6.返回顶部   作者:ylbtech出 ...

  3. CodeForces - 504A && CodeForces - 624C && CodeForces - 2B

    Points 1. 关键要看到以度数为1的点作为突破口. 2. 关键是发现两者不同只能是a-c,而剩余的点必须为b 3. 注意0的情况.

  4. J20170414-ms

    ストレージ   仓库  

  5. POJ2365【几何】

    因为给出的点已经是顺时针了, 整个长度=相邻点距离+一个圆周长: C++ac代码-G++wa-因为标准不一样.G++用f //#include <bits/stdc++.h> #inclu ...

  6. 搜狗输入法ubuntu

    1.下载搜狗输入法的安装包 下载地址为:http://pinyin.sogou.com/linux/ ,如下图,要选择与自己系统位数一致的安装包,我的系统是64位,所以我下载64位的安装包 2.按键C ...

  7. Centos 6.x 搭建 Zabbix Server

      zabbix(音同 zæbix)是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案. zabbix能监视各种网络参数,保证服务器系统的安全运营:并提供灵活的通知机制以让 ...

  8. 关于在@Controller所返回的视图的css,js文件404问题

    本人在使用layui打开一个请求后台的页面时,页面成功由controller重定向到了正确的位置,然而几乎所有的js文件和css文件都报404,并且确定这些css文件还有js文件的引入的路径都是正确的 ...

  9. pscp多线程传输文件

    前面说过pscp不支持多线程,所以在此特地实现了一个 程序分三个部分: 1.初始化各种参数,涉及getopt函数的使用 2.重新定义scp,实现传递IP然后远程拷贝 3.启动多线程调用scp,涉及多线 ...

  10. AJPFX简述JavaStringBuffer方法

    以下是StringBuffer类支持的主要方法: 序号 方法描述 1 public StringBuffer append(String s)将指定的字符串追加到此字符序列. 2 public Str ...