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文件中定义的内容。

原文地址:https://www.cnblogs.com/OpenCoder/p/9827694.html

时间: 2024-08-29 19:29:16

ASP.NET Core 如何设置发布环境的相关文章

《ASP.NET Core 高性能系列》环境(EnvironmentName)的设置

原文:<ASP.NET Core 高性能系列>环境(EnvironmentName)的设置 一.概述 程序启动时Host捕获到环境相关数据,然后交由IEnvironment(传说要作废,但是觉得这个设计依旧前后矛盾,因为没有考虑好非Web 和Web区分),然后交由IWebHostEnvironment,对于ASP.NET Core环境而言,同样会存储在 IWebHostEnvironment.EnvironmentName,ASP.NET Core框架自身提供Development.Stagi

用&quot;hosting.json&quot;配置ASP.NET Core站点的Hosting环境

通常我们在 Prgram.cs 中使用硬编码的方式配置 ASP.NET Core 站点的 Hosting 环境,最常用的就是 .UseUrls() . public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseUrls("http://*:5000") .UseKestrel() .UseContentRoot(Directory.GetCurr

利用一个ASP.NET Core应用来发布静态文件

虽然ASP.NET Core是一款"动态"的Web服务端框架,但是在很多情况下都需要处理针对静态文件的请求,最为常见的就是这对JavaScript脚本文件.CSS样式文件和图片文件的请求.针对不同格式的静态文件请求的处理,ASP.NET Core为我们提供了三个中间件,它们将是本系列文章论述的重点.不过在针对对它们展开介绍之前,我们照理通过一些简单的实例来体验一下如何在一个ASP.NET Core应用中发布静态文件.[本文已经同步到<ASP.NET Core框架揭秘>之中]

菜鸟入门【ASP.NET Core】1:环境安装

下载.NET Core SDK 下载地址:https://www.microsoft.com/net/download/windows https://www.microsoft.com/net/learn/get-started/windows 安装vs2017,安装的时候选择安装core跨平台 在程序安装后,可以在控制台输入dotnet进行创建core应用程序 输入dotnet  --help查看命令帮助 .NET 命令行工具 (2.1.2) 使用情况: dotnet [runtime-op

总结:利用asp.net core日志进行生产环境下的错误排查(asp.net core version 2.2,用IIS做服务器)

概述 调试asp.net core程序时,在输出窗口中,在输出来源选择“调试”或“xxx-ASP.NET Core Web服务器”时,可以看到类似“info:Microsoft.AspNetCore.Hosting.Internal.WebHost[2] Request finished in 285.6ms 200 text/css”这样的内容,这就是asp.net core的日志 如果出现了未捕获的异常,在输出窗口中可以看到出错信息,如:fail: Microsoft.AspNetCore.

Asp.net Core 初探(发布和部署Linux)

前言 俗话说三天不学习,赶不上刘少奇.Asp.net Core更新这么长时间一直观望,周末帝都小雨,宅在家看了下Core Web App,顺便搭建了个HelloWorld环境来尝尝鲜,第一次看到.Net Web运行在Linux上还是有点小激动(只可惜微软走这一步路走的太晚,要不然屌丝们也不会每每遇见Java VS .Net就想辩论个你死我活). 开发环境和部署环境 Windows 10.VS2015 Update3.安装.Net Core SDK.DotNetCore.1.0.1-VS2015T

ASP.NET Core 2.1发布/部署到Ubuntu并配置Nginx反向代理实现ip访问

一.准备 我用的是Ubuntu服务器器 [Ubuntu 18.04 x64] 和终端管理工具[Xshell] 二.安装 在服务器上安装.NET Core 三.部署程序 1.创建实例程序 可以直接使用.NET Core 的命令创建一个ASP.NET Core 示例网站应用程序,创建目录 /home/myuser/firstapp,执行命令: dotnet new mvc 接着,发布刚才创建的ASP.NET Core 网站发网站目录,所以,我们先创建一个网站发布目录:/var/www/firstap

ASP.NET Core 配置和使用环境变量

前言 通常在应用程序开发到正式上线,在这个过程中我们会分为多个阶段,通常会有 开发.测试.以及正式环境等.每个环境的参数配置我们会使用不同的参数,因此呢,在ASP.NET Core中就提供了相关的环境API,方便我们更好的去做这些事情. 环境 ASP.NET Core使用ASPNETCORE_ENVIRONMENT来标识运行时环境. ASP.NET Core预设环境 Development:开发环境 Staging:暂存环境(测试环境) Production:正式环境 要取得系统变量ASPNET

ASP.Net Core中设置JSON中DateTime类型的格式化(解决时间返回T格式)

最近项目有个新同事,每个API接口里返回的时间格式中都带T如:[2019-06-06T10:59:51.1860128+08:00],其实这个主要是ASP.Net Core自带时间格式列化时间格式设置的,我们只需要替换序格式化时间格式就可以: 一.先建一个控制器测试: public IActionResult Get() { UserInfo userInfo = new UserInfo() { Name = "lxsh", BirthDay = DateTime.Now }; re