Net Core MVC6 RC2 启动过程分析
入口程序
如果做过Web之外开发的人,应该记得这个是标准的Console或者Winform的入口。为什么会这样呢?
.NET Web Development and Tools Blog
ASP.NET Core is a console app In RC1 an ASP.NET application was a class library that contained a Startup.cs class. When the DNX toolchain run your application ASP.NET hosting libraries would find and execute the Startup.cs, booting your web application. Whilst the spirit of this way of running an ASP.NET Core application still exists in RC2, it is somewhat different.
As of RC2 an ASP.NET Core application is a .NET Core Console application that calls into ASP.NET specific libraries. What this means for ASP.NET Core apps is that the code that used to live in the ASP.NET Hosting libraries and automatically run your startup.cs now lives inside a Program.cs. This alignment means that a single .NET toolchain can be used for both .NET Core Console applications and ASP.NET Core applications. It also means that customers have more obvious control over the code that hosts and runs their ASP.NET Core app:
翻译过来的意思大概是:
ASP.NET Core 在RC1的时候,是一个Console 应用程序,一个ASP.NET程序是一个包含有Startup.cs的类的类库。
当DNX(.NET运行环境)运行你的ASP.NET程序,它将会尝试去找到并且运行你的Stratup类,启动你的网站程序。这种启动方法任然在RC2中保留了下来,但是多少有些不同。
因为RC2是所谓的ASP.NET Core的应用程序,它是一种.NET Core 控制台(Console)程序,他被一些ASP.NET特殊的类所调用。这就意味着 ASPNET Core 原来存活在ASP.NET宿主库里面,自动执行Startup.cs的机制有所变化。
RC2的ASPNET Core变成了存活在一个控制台(Console)程序的程序,所有由Program.cs作为调用的入口了。
这样的话,整个.NET的工具链就变得内部执行机制统一了,即可以执行普通的 .NET Core Console 程序,也可以执行ASP.NET Core程序。
对于开发者和用户来说,也带来了一些控制和管理上的灵活性。
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build(); host.Run();
}
}
这里反复强调了一个宿主的概念。原来的MVC5时代,宿主应该是IIS服务器。
现在MVC6时代,宿主变成了一个普通的控制台程序了。当然,Web程序毕竟是需要一个WebHost运行环境的。UseKestrel,UseIISIntegration就是这样的环境。如果从Beta版开始关注的话,应该对于Kestrel不陌生,这个东西是一个迷你的HTTP服务器,可以让ASP程序HOST在上面运行。
注意:KestrelHttpServer,如果Baidu的话,一般出现这样的结果。请使用完整的关键字进行查询。
Kestrel 是 Scala 的一个非常小的队列系统,基于 starling。
Startup.cs
启动的前三句,分别涉及到Kestrel服务器,IIS集成,ContentRoot(内容的根目录,这里多说一句,现在的工程,解决方案的概念开始弱化了,取而代之的是文件夹的概念。可能和Nodejs的兴起有关。代码的组织形式更加自由了)
第四句则是和StartUp有关。
StartUp泛型
这里的StartUp虽然使用了泛型,但是如果看一下方法定义:TStartup只是约束为class
//
// Summary:
// Specify the startup type to be used by the web host.
//
// Parameters:
// hostBuilder:
// The Microsoft.AspNetCore.Hosting.IWebHostBuilder to configure.
//
// Type parameters:
// TStartup:
// The type containing the startup methods for the application.
//
// Returns:
// The Microsoft.AspNetCore.Hosting.IWebHostBuilder.
public static IWebHostBuilder UseStartup<TStartup>(this IWebHostBuilder hostBuilder) where TStartup : class;
我们来看一下StartUp里面到底做了什么
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
} builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
SetBasePath,还是要设定一下全局的路径。还记得MVC5的时代,Server.Map方法,将虚拟路径和实际路径进行转换,我猜测这里也是为了这样的方法做准备。
AddJsonFile,这个就是将JSON文件格式的配置文件放入总的配置管理器中。
具体的配置问题,请参看下面这篇文章
(1-2)配置的升级 - ASP.NET从MVC5升级到MVC6
AddUserSecrets,这个是RC新的配置。
以下引用自 解读ASP.NET 5 & MVC6系列(5):Configuration配置信息管理 更多UserSecrets,请阅读原文。
敏感信息配置(RC版新增功能)
在RC版发布以后,微软又新增了一种敏感信息配置实现,程序集为Microsoft.Framework.ConfigurationModel.UserSecrets,通过该程序集的管理,我们可以将敏感的配置信息放在计算机的特殊目录下的secrets.json文件,其目录定义规则如下:
Windows: %APPDATA%\microsoft\UserSecrets\\secrets.json
Linux: ~/.microsoft/usersecrets/\secrets.json
Mac: ~/.microsoft/usersecrets/\secrets.json
AddEnvironmentVariables:可以将操作系统的环境变量添加到配置系统中,同时你也可以对这些环境变量进行自定义
添加服务
除了StartUp方法,下面两个方法也是被系统(Runtime)自动调用的。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) // 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)
和整个系统相关的,有两件事情,一个是系统提供什么服务,当然这里是你可以自定义的,还有一件事情是,系统要怎么做LOG日志。
虽然这样说并不能很好的解释上面两个方法,但是大概就是这么回事。当然配置里面日志只是一个项目,MVC路由也可以作为配置项写在Configure里面的。
打开WebHostBuilder的源代码:这里就关心两件事情Service和Logger:服务和日志
(小知识,阶层型的配置文件,现在用冒号表示阶层关系了)
namespace Microsoft.AspNetCore.Hosting
{
/// <summary>
/// A builder for <see cref="IWebHost"/>
/// </summary>
public class WebHostBuilder : IWebHostBuilder
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly List<Action<IServiceCollection>> _configureServicesDelegates;
private readonly List<Action<ILoggerFactory>> _configureLoggingDelegates; private IConfiguration _config = new ConfigurationBuilder().AddInMemoryCollection().Build();
private ILoggerFactory _loggerFactory;
private WebHostOptions _options; /// <summary>
/// Initializes a new instance of the <see cref="WebHostBuilder"/> class.
/// </summary>
public WebHostBuilder()
{
_hostingEnvironment = new HostingEnvironment();
_configureServicesDelegates = new List<Action<IServiceCollection>>();
_configureLoggingDelegates = new List<Action<ILoggerFactory>>(); // This may end up storing null, but that's indistinguishable from not adding it.
UseSetting(WebHostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
// Legacy keys, never remove these.
?? Environment.GetEnvironmentVariable("Hosting:Environment")
?? Environment.GetEnvironmentVariable("ASPNET_ENV")); if (Environment.GetEnvironmentVariable("Hosting:Environment") != null)
{
Console.WriteLine("The environment variable 'Hosting:Environment' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'");
}
if (Environment.GetEnvironmentVariable("ASPNET_ENV") != null)
{
Console.WriteLine("The environment variable 'ASPNET_ENV' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'");
}
}
服务的添加
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders(); services.AddMvc(); // Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
这里顾名思义:
- AddDbContext:数据库服务
- AddIdentity:身份认证服务
- AddMvc:MVC核心服务
- IEmailSender,ISmsSender :邮件和短信服务
配置
// 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.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
} app.UseStaticFiles(); app.UseIdentity(); // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715 app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
- loggerFactory:日志
- UseStaticFiles :静态文件 (注意:有些文件还是需要在WebConfig里面配置的,例如JSON,字体文件等等,不然估计还是404错误)
- UseIdentity:身份识别
- UseMvc:路由(核心中的核心功能)
EnvironmentName
还有一个问题是系统是如何获得EnvironmentName的。
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic;
using Microsoft.AspNet.FileSystems;
using Microsoft.Framework.Runtime; namespace Microsoft.AspNet.Hosting
{
public class HostingEnvironment : IHostingEnvironment
{
private const string DefaultEnvironmentName = "Development"; public HostingEnvironment(IApplicationEnvironment appEnvironment, IEnumerable<IConfigureHostingEnvironment> configures)
{
EnvironmentName = DefaultEnvironmentName;
WebRoot = HostingUtilities.GetWebRoot(appEnvironment.ApplicationBasePath);
WebRootFileSystem = new PhysicalFileSystem(WebRoot);
foreach (var configure in configures)
{
configure.Configure(this);
}
} public string EnvironmentName { get; set; } public string WebRoot { get; private set; } public IFileSystem WebRootFileSystem { get; set; }
}
}
通过源代码我们知道有一个默认的“Development”
我们如何设定这个EnvironmentName?
stackoverflow上面的回答:
how-to-set-ihostingenvironment-environmentname-in-vnext-application
这里使用了直接设定的方法(以下代码段并非针对 .NETCore RC2)
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
Configuration = new Configuration()
.AddJsonFile("config.json").AddEnvironmentVariables(); Configuration.Set("ASPNET_ENV","Your own value");
}
估计也可以写在Config的文件中。
<configuration>
<system.webServer>
<handlers>
<add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
</handlers>
<httpPlatform processPath="..\approot\web.cmd" arguments="--ASPNET_ENV Development" stdoutLogEnabled="false" stdoutLogFile="..\logs\stdout.log" startupTimeLimit="3600"></httpPlatform>
</system.webServer>
</configuration>
当然如果你去看最新版的代码,这里的环境变量关键字变成了 “ASPNETCORE_ENVIRONMENT”
(Hosting:Environment 和 ASPNET_ENV 都是旧的关键字了)
/// <summary>
/// Initializes a new instance of the <see cref="WebHostBuilder"/> class.
/// </summary>
public WebHostBuilder()
{
_hostingEnvironment = new HostingEnvironment();
_configureServicesDelegates = new List<Action<IServiceCollection>>();
_configureLoggingDelegates = new List<Action<ILoggerFactory>>(); // This may end up storing null, but that's indistinguishable from not adding it.
UseSetting(WebHostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
// Legacy keys, never remove these.
?? Environment.GetEnvironmentVariable("Hosting:Environment")
?? Environment.GetEnvironmentVariable("ASPNET_ENV")); if (Environment.GetEnvironmentVariable("Hosting:Environment") != null)
{
Console.WriteLine("The environment variable 'Hosting:Environment' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'");
}
if (Environment.GetEnvironmentVariable("ASPNET_ENV") != null)
{
Console.WriteLine("The environment variable 'ASPNET_ENV' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'");
}
}
总结
- 为了统一结构和启动机制,ASP.NET Core程序也是一种Console程序。
- 配置文件多样化,JSON,XML,INI格式文件都是被支持的
- IIS还是需要Webconfig文件的
- 整个程序的入口不是RC1的StartUp了。
参考
Net Core MVC6 RC2 启动过程分析的更多相关文章
- ASP.Net Core MVC6 RC2 启动过程分析[偏源码分析]
入口程序 如果做过Web之外开发的人,应该记得这个是标准的Console或者Winform的入口.为什么会这样呢? .NET Web Development and Tools Blog ASP.NE ...
- ASP.NET从MVC5升级到MVC6 RC2 总目录 - 发布在RC2Release之后
序言 随着MVC6RC2的推出,MVC6的脚步越来越近了.但是在我们的手里,有大批量的MVC5的项目.如何将MVC5升级到MVC6,将是一个很大的课题.微软官方暂时没有一个升级指导,或者一个迁移工具, ...
- 【Bootloader】bootloader启动过程分析
Boot Loader启动过程分析 一. Boot Loader的概念和功能 1.嵌入式Linux软件结构与分布在一般情况下嵌入式Linux系统中的软件主要分为以下及部分: (1)引导加载程序: ...
- startActivity启动过程分析(转)
基于Android 6.0的源码剖析, 分析android Activity启动流程,相关源码: frameworks/base/services/core/java/com/android/serv ...
- 开机SystemServer到ActivityManagerService启动过程分析
开机SystemServer到ActivityManagerService启动过程 一 从Systemserver到AMS zygote-> systemserver:java入层口: /** ...
- Neutron分析(2)——neutron-server启动过程分析
neutron-server启动过程分析 1. /etc/init.d/neutron-server DAEMON=/usr/bin/neutron-server DAEMON_ARGS=" ...
- linux视频学习7(ssh, linux启动过程分析,加解压缩,java网络编程)
回顾数据库mysql的备份和恢复: show databases; user spdb1; show tables; 在mysql/bin目录下 执行备份: ./mysqldump -u root - ...
- Activity启动过程分析
Android的四大组件中除了BroadCastReceiver以外,其他三种组件都必须在AndroidManifest中注册,对于BroadCastReceiver来说,它既可以在AndroidMa ...
- Spark Streaming应用启动过程分析
本文为SparkStreaming源码剖析的第三篇,主要分析SparkStreaming启动过程. 在调用StreamingContext.start方法后,进入JobScheduler.start方 ...
随机推荐
- 线程相关函数(7)-sem_post(), sem_wait() 信号量
sem_tsem_initsem_waitsem_trywaitsem_timedwaitsem_postsem_destroy 生产者消费者实例: #include <stdlib.h> ...
- ov5640 i2c通信异常问题
1 异常场景如下描述 之前的测试场景: 将插在排针上的杜邦线向上拔一点,留出空间挂示波器的探针. 这种方式会导致i2c只发送一组8bit的数据,而另外两组没有发送成功.如上图所示. 因此,之前出现没有 ...
- MacBook Air 2014 安装win7
1.准备一个4G以上容量USB3.0 U盘.制作一个带USB3.0驱动的win7 2.将制作好的win7iso镜像文件复制到macbook上,插上U盘,运行Boot Camp助理: 3.选择默认勾选项 ...
- 在编写JSP的时候出现XXX cannot be resolved to a type
今天遇到这个情况,却发现是eclipse抽风,说javax.servlet.http.Cookie找不到定义,但是经过浏览器测试,可以运行,而JSP源文件中eclipse死活要报错.表示无语. 关于e ...
- [driver]简单地hello驱动加载
转自:http://blog.chinaunix.net/uid-24264134-id-98061.html Linux设备驱动会以内核模块的方式出现,因此,内核模块也成了我们编写驱动的入门知识,这 ...
- PHP——数组和数据结构
<body> <?php $arr[0]=5;//赋值定义 $arr[1]="aa"; print_r($arr); echo "<br /> ...
- springboot集成jdbcTemplate
这里使用springboot自带的jdbcTemplate连接mysql数据库 1. 添加依赖包 <!-- jdbc --> <dependency> <groupId& ...
- svn提示out of date
你需要先update一下,应该会有一个冲突标志,你查看一下历史日志,找到是谁在你之前进行了提交,和他商议一下如何合并你们两个人的修改,然后在你本地处理后,标记“冲突已解决”,最后再次commit
- 2015 Multi-University Training Contest 3 1001 Magician
Magician Problem's Link: http://acm.hdu.edu.cn/showproblem.php?pid=5316 Mean: n个数,2种操作,1是单点更新,2是询问区间 ...
- 【BZOJ】1618: [Usaco2008 Nov]Buying Hay 购买干草(dp)
http://www.lydsy.com/JudgeOnline/problem.php?id=1618 裸的01背包,注意背包的容量不是v即可. #include <cstdio> #i ...