An overview,

There are several stages in the process from development to launch, usually development, testing, and launch. We will use different parameters for the configuration of environment parameters corresponding to each stage. For example, the connection string of the database, the development environment generally we are the connection test library. In the past, two configuration files with the same name were copied for processing, and the local configuration was used locally, while the production environment used the configuration file in the production environment, which was very troublesome. ASP.net CORE uses environment variables to dynamically configure JSON files to support such requirements, making it easier for us to do these things.

ASP.NET Core environment

ASP.NET Core uses ASPNETCORE_ENVIRONMENT to identify the runtime environment.

ASP.NET Core uses environment variables to configure application behavior based on the runtime environment.

Software Development Environment Within a software development organization, we typically have the following development environment.

  • Development-> Development environment
  • Staging-> Demo (simulation, Staging) environment
  • Production-> Production environment

Why do we need different development environments such as development, demo, production, etc.

** Development environment: ** Our software developers typically use this environment for our daily development work. We want to load non-miniaturized JavaScript and CSS files in the development environment for easy debugging. Similarly, if there is an unhandled exception, we need a developer exception page so that we can understand the root cause of the exception and fix it if needed.

** Demo environment: ** Many organizations or companies try to keep their demo environment as close to the actual production environment as possible. The main reason for this environment is to identify any deployment-related issues. In addition, if you are developing B2B (business-to-business) applications, you may be connecting to other service provider systems. Many organizations typically set up their AD hoc environments to interact with service providers for complete end-to-end testing. We don’t normally do troubleshooting and debugging in a demo environment, and we need to load miniaturized JavaScript and CSS files for better performance. If there is an unhandled exception, display a user-friendly error page instead of a developer exception page. The user-friendly error page does not contain any technical details. It contains the following generic message: “Problems arise, please use the contact details below to email, chat or call our application support”

** Production environment: ** The actual environment we use for our daily business. The production environment should be configured for maximum security and performance. Therefore, load miniaturized JavaScript and CSS files to improve performance. For better security, display a user-friendly error page instead of a developer exception page. The technical details on the Developer Exception page are not meaningful to the end user, and malicious users can use them to gain access to your application.

In the startup. cs file in the Asp.NET Core project, you can use methods to control the behavior of your application. Here is the default code generated by the startup. cs file when creating the sample program:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id? }");
        });
    }
Copy the code

The variable of type IWebHostEnvironment represents the environment in which the application is currently running. ASP.Net Core provides four extension methods to check the current value of “ASPNETCORE_ENVIRONMENT”.

IsDevelopment() IsStaging() IsProduction() IsEnvironment()

If you need to check whether your application is running in a particular environment, you can use env.isEnvironment (” environmentName “), This method ignores case (please do not use env.environmentName == “Development” to check the environment).

On the following code, we can know, if the current is the development environment, using UseDeveloperExceptionPage () method error page processing, enable the development environment that helps us in the development process of debugging; However, in a production environment we do not want to enable these functions, and instead point the Error page to the path “/home/error” to display a user-friendly Error interface.

LaunchSettings. Json file

ASP.Net Core contains a new launchsettings. json file that you can find in the “Properties” folder in your project:

This file sets up the different environments that Visual Studio can launch in. Here is the default code generated by the LaunchSettings. json file in the sample project:

{
  "iisSettings": {
    "windowsAuthentication": false."anonymousAuthentication": true."iisExpress": {
      "applicationUrl": "http://localhost:53445"."sslPort": 0}},"profiles": {
    "IIS Express": {
      "commandName": "IISExpress"."launchBrowser": true."environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"}},"WebApplication1": {
      "commandName": "Project"."dotnetRunMessages": "true"."launchBrowser": true."applicationUrl": "http://localhost:5000"."environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"}}}}Copy the code

Here, there are two configuration nodes: IIS Express and WebApplication1, which correspond to the Visual Stuido start debug button drop-down options respectively:

The aunchSettings.json file is used to set up the environment in which to run the application in Visual Stuido. We can also add a node whose name is automatically added to the dropdown of the Visual Stuido debug button.

{
  "iisSettings": {
    "windowsAuthentication": false.// Whether to enable Windows authentication
    "anonymousAuthentication": true.// Enable anonymous authentication
    "iisExpress": {
      "applicationUrl": "http://localhost:53445".// The Url to start the application.
      "sslPort": 0  // Enable SSL port}},"profiles": {
    "IIS Express": {
      "commandName": "IISExpress"."launchBrowser": true.// Whether to start in a browser
      "environmentVariables": { // Set environment variables to key/value pairs
        "ASPNETCORE_ENVIRONMENT": "Development"}},"WebApplication1": {
      "commandName": "Project"."dotnetRunMessages": "true"."launchBrowser": true."applicationUrl": "http://localhost:5000"."environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"}}}}Copy the code

CommandName specifies the Web server to start. CommandName can be any of the following:

  • IISExpress
  • IIS
  • Project

More detailed information of attribute to understand through this link: json.schemastore.org/launchsetti… .

The “debug” TAB of the Visual Studio project properties provides a GUI for editing the LaunchSettings. json file. Changes made to the project configuration file may not take effect until the Web server is restarted. Kestrel must be restarted to detect changes made to its environment.

To obtain the system variable ASPNETCORE_ENVIRONMENT, it can be obtained by injecting IHostingEnvironment prior to 3.0, or by injecting IWebHostEnvironment between 3.x and 5.0, as shown in the following code snippet:

public class Startup
{
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
        }

        app.Run(async (context) =>
                {
                    await context.Response.WriteAsync(
                        $"EnvironmentName: {env.EnvironmentName},IsDevelopment: {env.IsDevelopment()}"); }); }}Copy the code

The IWebHostEnvironment gets the content from ASPNETCORE_ENVIRONMENT once the site is started. This variable can be any value we need and can be customized. For example, let’s define an environment called Test:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            env.EnvironmentName = "test";

            if (env.IsDevelopment())
            {
                //TODO
            }else if (env.IsEnvironment("text"))
            {
                //TODO
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync(
                    $"EnvironmentName: {env.EnvironmentName},IsDevelopment: {env.IsDevelopment()}"
                );
            });
  }
Copy the code
Note: On Windows and macOS, environment variables and values are case insensitive. By default, Linux environment variables and values are case sensitive.Copy the code

Application examples

We have a good understanding of the environment variables in.net Core. Now let’s use a common example: database connection string fetching in different environments.

Start by defining different environments in launchsettings. json, as shown below:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:53445",
      "sslPort": 0
    }
  },

  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },    
    "WebApplication-Development": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebApplication-Production": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    }
  }
}
Copy the code

Different environments are specified, and each environment corresponds to a configuration file, as shown below:

Define a configuration item in different configuration files with different values, as shown in the following figure:

Add output to startup. cs code to get the corresponding values for different running configuration files, as follows:

Console.WriteLine("Connection in current environment:" + Configuration.GetSection("ConnectionString:Default").Value);
Copy the code

Run in different environments and see what the Settings look like:

Run in a development environment:

Run in production environment:

Through this simple example, we have understood the configuration of the environment and the use of the process, WE believe that based on this, can be applied to the actual project. In ASP.NET Core, developers can easily control the behavior of applications in different environments using environment variables.

Reference article:

.net Core deployed to Linux (CentOS) most complete solution, general chapter

.net Core Deployment for Linux (CentOS) Supervisor+Nginx

Docker+Nginx or Jexus

.net Core deployment to Linux (CentOS) most complete solution, into the devil (using Docker+Jenkins to achieve continuous integration, automatic deployment)

This article covers the use of Virtual machine VirtualBox and Linux

Common Linux commands are required for development

New cross-platform version. NET agile development framework -RDIFramework.NET5.0 shock release

NET Core is the most complete solution for deploying to Windows IIS

Use multiple environments in ASP.NET Core


Over the years, thanks to supporters and users of the RDIFramework.NET framework, you can find out more at the following address.

RDIFramework.NET official website: www.rdiframework.net/

RDIFramework.NET official blog: blog.rdiframework.net/

Special note, the framework related technical articles please refer to the official website prevail, welcome everyone to collect!

RDIFramework.NET is built by the professional team of Hainan Guosi Software Technology Co., LTD., which has been updated for a long time. Please feel free to use it!

Please follow the official wechat account of RDIFramework.NET (wechat id: Guosisoft) to keep abreast of the latest developments.

Use wechat to scan the QR code for immediate attention