Working in multiple environments

Source: Internet
Author: User
Tags configuration settings

Working in multiple environments

Original: Working with multiple environments
Steve Smith
Translation: Liu Haoyang
Proofreading: Meng Liang (book edge)

ASP. NET Core describes improvements that support the management of application behavior in multiple environments, such as development (development), rehearsal (staging), and production (production). Environment variables are used to indicate the environment in which the application is running, allowing the application to be configured appropriately.

Chapter:

    • Development, rehearsal, production
    • Determining the environment at run time
    • Start Convention
    • Profile
    • Additional Resources

View or download sample code

Development, rehearsal, production

ASP. NET Core refers to a specific environment variable that ASPNETCORE_ENVIRONMENT describes the environment in which the application is currently running. This variable can be set to any value you like, but there are three values that are agreed to use: Development , Staging and Production . You will find that these values are used in the samples and templates provided by ASP.

The current environment settings can be detected programmatically from the application. In addition, you can use the Environment Tag helper in your view to include some parts based on your current application environment.

Attention
The specified environment variable name is case insensitive. Regardless of whether you set the variable to Development or development or DEVELOPMENT the result will be the same.

Development

This should be the environment used when developing the application. When using Visual Studio, this setting can be specified in the project's debug configuration file, such as IIS Express, which is shown here:

When you modify the default settings that the project creates, your changes are kept in the Properties folder's Launchsettings.json file. This file contains specific settings for each configuration file in Visual Studio that is used to launch the application, including any environment variables that should be used. (The Debug configuration file is discussed in more detail in servers.) For example, to add another profile configuration to use IIS Express, use Staging ASPNETCORE_ENVIRONMENT the as value in our sample project launchSettings.json as shown in the file:

Copy Code
{"Iissettings ":{"WindowsAuthentication ":False,"Anonymousauthentication ":True,"Iisexpress ":{"ApplicationUrl ":"Http://localhost:40088/","Sslport ":0}},"Profiles:{"IIS Express ":{"CommandName ":"Iisexpress","Launchbrowser ":True,"Environmentvariables ":{"Aspnetcore_environment ":"Development"} }, "IIS Express (Staging)": { "commandName": "iisexpress", "  Launchbrowser ": true, "environmentvariables ": { "aspnetcore_ Environment ": " Staging "            }}}} 

Attention
Changes made to the project configuration file or Launchsettings.json may not take effect directly before the Web server being used is restarted (especially if the kestrel must be restarted before the environment that will detect it changes).

You can create several different boot configurations for different profiles of your application, including other environment variables that they require.

Warning
Environment variables stored in Launchsettings.json are not secure and will be part of your application's source code repository if you use one of them. do not store certificates or other security data in this file. If you need a place to store this data, use the Secret Manager tool described in Safe storage of app secrets during development.

Preview

By convention, the Staging environment is a pre-production environment for final testing before deploying to a production environment. Ideally, its physical characteristics should be a true portrayal of the production environment, so any problems that may arise in the production environment occur first in the staging environment, where they can be resolved without affecting the user.

Production

ProductionAn environment is an environment in which an application runs, is active, and is used by end users. This environment should be configured to maximize security, performance, and robustness of the application. Some common settings for a production environment that are different from the development environment include:

    • Enable caching
    • Ensure that all client resources are packaged, compressed and provided as much as possible from the CDN
    • Close the Diagnostic error page
    • Enable friendly error page
    • Enable production logging and monitoring (ex: Application Insights)

This is not a complete list. It is best to avoid the clutter of the environment in all parts of your application. Instead, the recommended approach is Startup to make such checks in the application's class as much as possible.

Determining the environment at run time

The Ihostingenvironment service provides the core abstraction for the work environment. The service is provided by the ASP. NET host layer and can be injected into your startup logic via dependency injection. The ASP. NET Core site template in Visual Studio uses this method to load a specific environment profile, if one exists, and to customize the application's error handling settings. In both cases, this behavior is implemented by referring to the Environmentname or isenvironment on the instance of Ihostingenvironment that is invoked by referencing the currently specified environment to be passed to the appropriate method.

Attention
If you need to check if the application is running in a particular environment, use env.IsEnvironment("environmentname") it because it ignores the case correctly (instead of checking for example env.EnvironmentName == "Development" ).

For example, you can use the following code to set the error handling for a particular environment in your configuration method:

Copy Code
public void Configure(IApplicationBuilder app, IHostingEnvironment env){ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } // ...

If the application is running in an Development environment, it opens the necessary run-time support in Visual Studio to use the browser link (browserlink) feature, A specific Development error page (which should not normally be run in production) and a specific Database error page (it provides a way to apply the migration, so it should only be used in development). Additionally, if the application is not running in the development environment, configure a standard error handling page to display any unhandled exceptions in the response.

You may need to determine at run time what you need to send to the client. For example, in a development environment you typically provide a non-minimized script and style sheet, which is easier to debug. In production and test environments, the minimum version should generally be provided from CND. You can use the Environment Tag helper to do this. If, of course, the environment names matches the environment specified using the attribute, the Environment Tag helper will only provide its contents.

Copy Code
<Environment names="Development"><Link Rel="Stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /><Link Rel="Stylesheet" href="~/css/site.css" /></Environment><Environment names="Staging,production"><Link Rel="Stylesheet" href="Https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css" asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css" asp-fallback-test-class="Sr-only" asp-fallback-test-property="Position" Asp-fallback-test-value="Absolute" /> <link rel="stylesheet" href=" ~/css/site.min.css " asp-append-version="true" /></environment>     

In your app start using tag helpers to view tag helper.

Start Convention

ASP. NET Core supports a contract-based approach to configure the startup of an application based on the current environment. Depending on which environment your application is in, you can also programmatically control the behavior of your application, allowing you to create and manage your own conventions.

When an ASP. NET Core application starts, the Startup class is used to boot the application, load its configuration settings, and so on (learn more about ASP. NET startup). However, if the name of a class exists Startup{EnvironmentName} (for example StartupDevelopment ), and the Hosting:Environment environment variable matches its name, then the class is used Startup .

In addition to using a fully independent startup class based on the current environment, you can also Startup make adjustments to how the application is configured in the class. Configure()and ConfigureServices() Method-like Startup classes that Configure[EnvironmentName]() Configure[EnvironmentName]Services() support the version of a particular environment in and of the form. When set to the development environment, if you define a ConfigureDevelopment() method, this method will be called instead of Configure() . Similarly, in the same environment will be called ConfigureDevelopmentServices() instead of ConfigureServices() .

Profile

ASP. NET Core provides a number of features and conventions that allow developers to control the behavior of their applications in different environments more easily. When releasing an application from development to rehearsal to production, setting the appropriate environment variables for the environment allows for proper optimization of the debugging, testing, or production use of the application.

Additional Resources
    • Configuration
    • Introduction to Tag Helpers

Working in multiple environments

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.