Asp.net Core Startup Class中是如何获取配置信息的
默认的网站构建方式
VS2015新建asp.net core项目,项目建立完成后,有两个文件,Program.cs
和Startup.cs
.
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
从入口函数开始,WebHost
构建网站时调用了Startup
类。再来看Startup.cs
文件
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
//Startup构造函数只由asp.net core框架调用第一个,所以下面这个构造方法不会执行。
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
其中,第二个构造函数是我自己加的,VS默认生成的是第一个构造函数。跟踪调试,第一个构造函数已经有configuration
对象传入进来,并且已经加载了配置信息。没有去翻asp.net core的源码,但是在文档中发现了这样一句话:
Remarks
The following defaults are applied to the returned WebHostBuilder: use Kestrel as the web server, set the ContentRootPath to the result of GetCurrentDirectory(), load IConfiguration from 'appsettings.json' and 'appsettings.[EnvironmentName].json', load IConfiguration from User Secrets when EnvironmentName is 'Development' using the entry assembly, load IConfiguration from environment variables, load IConfiguration from supplied command line args, configures the ILoggerFactory to log to the console and debug output, enables IIS integration, enables the ability for frameworks to bind their options to their default configuration sections, and adds the developer exception page when EnvironmentName is 'Development'
查看原文
原来,WebHostBuilder
在默认情况下,做了以下几件事:
- 使用了Kestrel作为Web服务器
- 加载appsettings.json和appsettings.[EnvironmentName].json
- 当Development环境下,会从User Secrets中加载用户私有数据
- 从环境变量中加载数据
- 从命令行参数中加载数据
- 加载控制台为日志输出
- 启用IIS integration
- ....
正是由于WebHostBuilder
帮助我们做了这么多处理,我们的网站才能够启动。
如何覆盖默认的构建方式
如上所述,WebHostBuilder帮我们完成了启动过程,那我们如何自定义我们的网站构建过程呢。
看上面代码中Startup.cs中的第二个构造函数,WebHostBuilder只会调用第一个构造函数,所以我们如果需要自定义,则需要把第二个构造函数放到最前。
这样我们就可以配置我们的配置文件加载方式、Web服务器等。