ASPNETCORE_ENVIRONMENT
ASP.NET Core控制环境切换最核心的东西是“ASPNETCORE_ENVIRONMENT”环境变量,它直接控制当前应用程序运行的环境类型。您可以通过在项目上右键菜单选择“属性”选项,然后切换到“调试”标签来修改此环境变量。

此环境变量框架默认提供了三个值,当然您也可以定义其它的值:
Development(开发)Staging(预演)Production(生产)我们在Startup.cs文件中,可以使用相应的方法来控制应用程序的行为。以下是创建示例程序时Startup.cs文件生成的默认代码:
// 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.UseBrowserLink(); } else { app.UseExceptionHandlwww.easck.comer("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }其中 IHostingEnvironment 类型的vxzzWuRvGm变量表示的是当前应用程序运行的环境,ASP.Net Core提供了四个扩展方法,用于检测 “ASPNETCORE_ENVIRONMENT”当前的值。
IsDevelopment()IsStaging()IsProduction()IsEnvironment()": { //将环境变量设置为键/值对 "ASPNETCORE_ENVIRONMENT": "Development" } } }}Environment 标签
通过这个标签,应用程序当根据当前运行的环境修改MVC视图的结构。在示例项目中_Layout.cshtml文件生成的默认代码:
<environment names="Development"> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" rel="external nofollow" /> <link rel="stylesheet" href="~/css/site.css" rel="external nofollow" /> </environment> <environment names="Staging,Production"> <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css" rel="external nofollow" asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" /> <link rel="stylesheet" href="~/css/site.min.css" rel="external nofollow" asp-append-version="true" /> </environment>
在这个示例中,当在开发模式下运行应用程序时,我们使用本地的Bootstrap文件和自定义css文件;但是如果在预演和生产环境中运行,我们则使用ASP.NET内容分发网络(CDN)上的文件副本和经过压缩过的自定义样式。通过这种方式,我们可以提高应用程序的性能。
总结
在ASP.NET Core中,开发者可以使用环境变量轻而易举控制应用程序在不同的环境中的行为。使用这些功能,我们完成以下功能:
创建和使用自定义环境;根据应用程序运行的环境启用或禁用应用程序部分功能;使用 environment 标签修改当前环境中MVC视图。到此这篇关于ASP.NET Core环境变量配置和启动设置的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。








