search
HomeBackend DevelopmentC#.Net TutorialNew features in ASP.NET Core--environment variables and startup settings

This article mainly introduces the configuration tutorial of ASP.NET Core environment variables and startup settings in detail. It has certain reference value. Interested friends can refer to it

In this part, we will discuss a new feature in ASP.NET Core: environment variables and startup settings, which will make debugging and testing during the development process easier. We only need to simply modify the configuration file to achieve switching between development, preview, and production environments.

ASPNETCORE_ENVIRONMENT

The core thing for ASP.NET Core to control environment switching is the "ASPNETCORE_ENVIRONMENT" environment variable, which directly controls the type of environment in which the current application is running. You can modify this environment variable by selecting the "Properties" option from the right-click menu on the project 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)

We can use the corresponding method in the Startup.cs file. Control application behavior. 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 type IHostingEnvironment represents the environment in which the current application is running, ASP.Net Core Four extension methods are provided for detecting the current value of "ASPNETCORE_ENVIRONMENT".

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

If you need to check this Whether the application is running in a specific environment, you can use env.IsEnvironment("environmentname"), which ignores case (please do not use env.EnvironmentName == "Development" to check the environment).

Through the above code, we can know that if it is currently a development environment, use the UseDeveloperExceptionPage() and UseBrowserLink() methods to enable the error page of the development environment and enable the Browser Link function in Visual Stuido. These All functions are helpful for us to debug the program during the development process; but in the production environment, we do not want to enable these functions, but point the error page to the path "/Home/Error" to display a friendly error interface to the user.

launchSettings.json file

ASP.Net Core includes a new file launchSettings.json, which you can find in the "Properties" folder in your project:

This file sets up different environments that Visual Studio can launch. 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 Visual Stuido start debugging button:

## The #launchSettings.json file is used to set the environment for running applications in Visual Stuido. We can also add a node and the node name will automatically be added to the drop down selection of the Visual Stuido debug button.

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


{
 "iisSettings": {
 "windowsAuthentication": false,//启用Windows身份验证
 "anonymousAuthentication": true,//启用匿名身份验证
 "iisExpress": {
 "applicationUrl": "http://localhost:22437/",//应用启动的Url路径。
 "sslPort": 44355//启用SSL的端口
 }
 },
 "profiles": {
 "IIS Express": {
 "commandName": "IISExpress",
 "commandLineArgs": "", //传递命令的参数
 "workingDirectory": "", //设置命令的工作目录
 "launchBrowser": true, //是否在浏览器中启动
 "launchUrl": "1111", //在浏览器中启动的相对URL
 "environmentVariables": { //将环境变量设置为键/值对
 "ASPNETCORE_ENVIRONMENT": "Development"
 }
 }
 }
}

To get the details of other more properties, please go to this link: http://json.schemastore.org/launchsettings.

Environment tag

Through this tag, the application modifies the structure of the MVC view according to the current running environment. The default code generated by the _Layout.cshtml file in the sample project:


<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 files and custom css files; but if running in staging and production environments, we use a copy of the files and compressed custom styles on the ASP.NET Content Delivery Network (CDN). In this way we can improve the performance of our application.

Summary

In ASP.NET Core, developers can use environment variables to easily control the behavior of applications in different environments. Using these features, we complete the following functions:

  • Create and use custom environments;

  • Enable or disable applications based on the environment in which they are running Some functions of the program;

  • Use the environment tag to modify the MVC view in the current environment.

The above is the detailed content of New features in ASP.NET Core--environment variables and startup settings. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.