ASP.NET Core 如何设置发布环境

在ASP.NET Core中自带了一些内置对象,可以读取到当前程序处于什么样的环境当中,比如在ASP.NET Core的Startup类的Configure方法中,我们就会看到这么一段代码:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
            
    app.UseStaticFiles();
    app.UseCookiePolicy();
            
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
}

其中env.IsDevelopment()就可以读出当前程序是否是处于开发环境当中,如果你在Visual Studio中运行ASP.NET Core项目那么上面的env.IsDevelopment()就会返回true,如果你发布(publish)了ASP.NET Core项目,并在IIS中运行发布后的项目代码,那么上面的env.IsDevelopment()就会返回false。

 

env.IsDevelopment()其实是IHostingEnvironment接口(IHostingEnvironment接口默认就注册在了ASP.NET Core的依赖注入容器中,可以在ASP.NET Core中任何需要用依赖注入的地方<例如,Startup类的构造函数,Startup类的Configure方法,Controller的构造函数,中间件、MVC视图等地方>使用IHostingEnvironment接口)的一个扩展方法,其定义在HostingEnvironmentExtensions这个扩展类中,可以看到HostingEnvironmentExtensions类定义了一些和ASP.NET Core运行环境相关的方法:

 

技术分享图片

其中

  • IsDevelopment方法用来检测ASP.NET Core项目当前是否处于开发环境,比如在Visual Studio中运行ASP.NET Core项目IsDevelopment方法就会返回true
  • IsProduction方法用来检测ASP.NET Core项目当前是否处于生产环境,比如将ASP.NET Core项目发布(publish)后,IsProduction方法就会返回true
  • IsStaging方法用来检测ASP.NET Core项目当前是否处于一个中间环境,比如如果项目还有测试环境,就可以将IsStaging方法用来检测ASP.NET Core项目是否处于测试环境

那么为什么在Visual Studio中运行ASP.NET Core项目,HostingEnvironmentExtensions类的IsDevelopment方法会返回true呢?我们打开ASP.NET Core项目Properties节点下的launchSettings.json文件

技术分享图片

其中的Json文本如下:

{
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:52028",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebCoreEnvironments": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

我们可以看到在profiles"有一个"IIS Express"节点,其中有一个"ASPNETCORE_ENVIRONMENT"属性,其值为Development,这就表示了当我们在Visual Studio中用IIS Express运行ASP.NET Core项目时,处于的是Development环境,所以此时HostingEnvironmentExtensions类的IsDevelopment方法会返回true。ASPNETCORE_ENVIRONMENT属性后面可以定义任何值,但是一般来说都定义为Development、Production和Staging三个值,对应的HostingEnvironmentExtensions类的三个方法,如果你定义了一个其它的值(比如Staging2),可以用HostingEnvironmentExtensions类的IsEnvironment方法进行检测,参数environmentName就是要检测的环境名(比如Staging2)。当发布ASP.NET Core项目后,ASPNETCORE_ENVIRONMENT属性的默认值会是Production,这就是为什么当ASP.NET Core项目发布后,HostingEnvironmentExtensions类的IsProduction方法会返回true。

 

此外ASPNETCORE_ENVIRONMENT属性的值还可以影响ASP.NET Core项目appsettings文件的读取,我们来看下面一个例子:

假设我们有个ASP.NET Core MVC项目叫WebCoreEnvironments,其中我们定义了两套appsettings文件:appsettings.Development.json和appsettings.Production.json,分别用于存放项目开发环境和生产环境的参数, appsettings.Development.json和appsettings.Production.json中都定义了一个属性叫TestString,不过两个文件存储的TestString属性值不同。

技术分享图片

appsettings.Development.json文件内容如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "AppSettings": {
    "TestString": "This is development environment"
  }
}

appsettings.Production.json文件内容如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "AppSettings": {
    "TestString": "This is production environment"
  }
}

 

接着我们在ASP.NET Core MVC项目中定义了一个AppSettings类用于读取和反序列化appsettings文件的内容:

技术分享图片

namespace WebCoreEnvironments.Models
{
    public class AppSettings
    {
        public string TestString { get; set; }
    }
}

其中就一个TestString属性和appsettings文件中的属性同名。

 

然后我们在Startup类中设置读取appsettings文件的代码,其中相关代码用黄色高亮标记了出来:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebCoreEnvironments.Models;

namespace WebCoreEnvironments
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = newConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)//这里采用appsettings.{env.EnvironmentName}.json根据当前的运行环境来加载相应的appsettings文件
                .AddEnvironmentVariables();

            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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddOptions();
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

可以看到我们在读取appsettings文件时,使用了AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)来根据当前ASP.NET Core项目所处的环境读取相应的appsettings文件,如果是开发环境就读取appsettings.Development.json,如果是生产环境就读取appsettings.Production.json。

 

然后我们在Index.cshtml视图文件(对应HomeController的Index方法)中定义了如下代码:

@{
    Layout = null;
}

@using Microsoft.AspNetCore.Hosting
@using Microsoft.Extensions.Options;
@using WebCoreEnvironments.Models

@inject IHostingEnvironment env
@inject IOptions<AppSettings> appSettings
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        Current environment is:@env.EnvironmentName
    </div>
    <div>
        Is this a development environment:@env.IsDevelopment().ToString()
    </div>
    <div>
        Is this a production environment:@env.IsProduction().ToString()
    </div>
    <div>
        TestString in AppSettings is :@appSettings.Value.TestString
    </div>
</body>
</html>

在Index.cshtml视图中我们使用@inject标签,让ASP.NET Core MVC依赖注入了IHostingEnvironment接口变量env和IOptions<AppSettings>接口变量appSettings,分别用于读取当前ASP.NET Core项目所处的环境和appsettings文件的内容。

接着我们用env.EnvironmentName、env.IsDevelopment和env.IsProduction三个HostingEnvironmentExtensions类的扩展方法来检测当前ASP.NET Core项目所处的环境

然后我们用appSettings.Value.TestString输出当前环境对应的appsettings文件中,TestString属性的值。

 

当我们在Visual Studio中运行项目时,访问Index.cshtml视图,浏览器结果如下:

技术分享图片

可以看到当前所处的环境是Development,所以env.IsDevelopment返回true,env.IsProduction返回false,并且appSettings.Value.TestString的值为我们在appsettings.Production.json文件中定义的内容。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值