Asp.net core environment variables and boot settings configuration tutorial

Time:2021-7-9

In this part, we will discuss a new function in asp.net core: environment variables and startup settings, which makes debugging and testing easier. We only need to modify the configuration file to switch the development, preview and production environment.

ASPNETCORE_ENVIRONMENT

The core of asp.net core control environment switching is “aspnet core”_ Environment variable, which directly controls the type of environment in which the current application is running. You can modify this environment variable by right clicking on the Project menu, selecting the properties option, and then switching to the debug tab.

This environment variable framework provides three values by default. Of course, you can also define other values:

Development(Development)
Staging(Preview)
Production(production)

In the startup.cs file, we can use corresponding methods to control the behavior of the application. The following is the default code generated by the startup.cs file when creating the sample program:


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

  app.UseStaticFiles();

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

The variable of ihostingenvironment type represents the running environment of the current application. ASP. Net core provides four extension methods to detect “aspnet core”_ The current value of environment.

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

If you need to check whether the application is running in a specific environment, you can use env.isenvironment (“environmentname”), which ignores case (do not use env.environmentname = = “development” to check the environment).

Through the above code, we can know that if the current development environment is used, use the usedeveloperexceptionpage() and usebrowserlink() methods to enable the error page of the development environment and the error page in visual stuidoBrowser LinkThese functions help us to debug programs in the development process. However, in the production environment, we do not want to enable these functions, but point the error page to the path “/ home / error” to show the user a friendly error interface.

Launchsettings.json file

ASP. Net core contains a new file called launchsettings.json, which can be found in the “properties” folder of the project

This file sets different environments in which visual studio can start. The following is the default code generated by the launchsettings.json file in the sample project:


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

Here, there are two configuration nodes: “IIS express” and “corewebapp”. These two nodes correspond to the drop-down options of the start debugging button of visual stuido

The launchsettings.json file is used to set the environment in which the application runs in visual stuido. We can also add a node whose name is automatically added to the drop-down option of the visual studio debug button.

Now let’s talk about the details of these attributes in detail

{
 "iisSettings": {
 "Windows authentication": false, // enable windows authentication
 "Anonymous authentication": true, // enable anonymous authentication
 "iisExpress": {
 "applicationUrl": " http://localhost:22437/ ", // url path of application startup.
 "Sslport": 44355 // SSL enabled port
 }
 },
 "profiles": {
 "IIS Express": {
 "commandName": "IISExpress",
 "Commandlineargs": '', // pass the parameters of the command
 "Working directory": "// sets the working directory of the command
 "Launchbrowser": true, // start in browser
 "Launchurl": "1111" // relative URL launched in browser
 "Environment variables": {// setting environment variables as key / value pairs
 "ASPNETCORE_ENVIRONMENT": "Development"
 }
 }
 }
}

For more information about other properties, go to this link:http://json.schemastore.org/launchsettings

Environment label

With this tag, the application can modify the MVC view structure according to the current running environment. In the sample project_ Default code generated by layout.cshtml file:


<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"
  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>

In this example, when running the application in development mode, we use the local bootstrap file and custom CSS file; However, if running in the preview and production environment, we use the copy of files on the asp.net content distribution network (CDN) and the compressed custom style. In this way, we can improve the performance of the application.

summary

In asp.net core, developers can easily control the behavior of applications in different environments by using environment variables. Using these functions, we complete the following functions:

  • Create and use custom environment;
  • According to the running environment of the application, some functions of the application can be enabled or disabled;
  • Use the environment tab to modify the MVC view in the current environment.

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.