Back to: ASP.NET Core Tutorials For Beginners and Professionals
Environment Tag Helper in ASP.NET Core MVC Application
I will discuss the Environment Tag Helper in ASP.NET Core MVC Application with Examples in this article. Please read our previous article, discussing the Image Tag Helper in ASP.NET Core MVC Application with Examples. As part of this article, we will discuss the following pointers.
1. Different Environments in Software Development
Development Environment
Staging Environment
Production Environment
2. Understanding the use of Environment Tag Helper in ASP.NET Core MVC Application
3. How to Set the Environment in ASP.NET Core MVC Application?
4. What is the use of Integrity in CDN Link?
5. What if the CDN is Down?
6. Multiple Examples to Understand the ASP.NET Core Environment Tag Helper
What is Environment Tag Helper in ASP.NET Core MVC?
The Environment Tag Helper in ASP.NET Core provides a way to conditionally render content in your views based on the hosting environment. This is particularly useful when displaying different content or behavior depending on whether your application runs in a development, staging, or production environment.
Different Environments in Software Development:
Nowadays, most software development organizations typically have the following three environments.
- Development Environment
- Staging Environment
- Production Environment
Development Environment:
The “Development Environment” refers to a specific stage in the software development lifecycle where developers create, test, and refine software applications before they are released to production. It’s the environment in which developers write and debug code, integrate different components, and ensure the application behaves as expected. The development environment is an isolated setup that facilitates efficient development and quality assurance processes.
As software developers, we generally use this development environment for our day-to-day development work. In this environment, we generally use non-minified JavaScript and CSS files for the purpose of easy debugging. Another use of this environment is that we want to show the developer exception page if there is an unhandled exception so that we can understand the root cause of the exception and then take necessary action to fix the issue.
Staging Environment:
A “Staging Environment” is a phase in the software development lifecycle that comes after the development environment and before the production environment. The staging environment serves as an intermediate testing ground where the application is tested in an environment that closely resembles the production environment. Its primary purpose is to identify and address any issues, bugs, or discrepancies before the application is deployed to actual users in the production environment.
The staging environment is very much similar to the production environment. Nowadays, many organizations use this staging environment to identify any deployment-related issues. Again, if you are developing a B2B (business-to-business) application, you may use services provided by other service providers. So, many organizations set up their staging environment to check the service providers as well for complete end-to-end testing.
We usually do not perform the debugging and troubleshooting in the staging environment, so we use minified JavaScript and CSS files to perform better. Again, if there is an exception, we need to show a friendly error page instead of showing the developer exception page. The friendly error page will not contain any technical exception details. Instead, it shows a generic error message like the one below.
“Something went wrong; our IT team is working on this to solve it as soon as possible. If you need further details, please Email, Chat, or Call our support team using the contact details below.”
Production Environment:
The “Production Environment” is the final phase in the software development lifecycle. The fully developed and thoroughly tested software application is deployed and made available to actual users or customers. The production environment is the live or operational environment where users interact with the application, and its stability, performance, and security are of utmost importance.
This is the live environment for the client or users to use for day-to-day business. The Production environment should be configured for maximum security and performance. So, in this environment, we also need to use the minified JavaScript and CSS files. For better security, we need to show a User-Friendly Error Page instead of the Developer Exception Page when an unhandled exception occurs in our application.
How to use the Environment Tag Helper in ASP.NET Core?
Basic Usage:
The basic usage of the Environment Tag Helper involves wrapping the content you want to render within <environment> tags conditionally. You can specify the environment(s) for which the content should be rendered using the include attribute.
<environment include="Development"> <!-- Content only visible in the Development environment --> </environment>
Specifying Multiple Environments:
You can specify multiple environments using a comma-separated list in the include attribute. The content will be rendered if the application runs in any specified environment.
<environment include="Development,Staging"> <!-- Content visible in the Development and Staging environments --> </environment>
Negating Environments:
You can use the exclude attribute to negate the environments for which the content should be rendered. The content will be rendered if the application is not running in the specified environment(s).
<environment exclude="Production"> <!-- Content not visible in the Production environment --> </environment>
The Environment Tag Helper is useful for various scenarios:
- Displaying debugging or diagnostic information in development environments.
- Including special behavior, such as logging or additional validation, during specific stages of your application’s lifecycle.
- Changing the appearance or behavior of UI elements based on the deployment environment.
Remember that the environment names (e.g., “Development”, “Staging”, “Production”) are typically configured in the appsettings.json or appsettings.{Environment}.json files of your ASP.NET Core application. The current environment is determined based on the ASPNETCORE_ENVIRONMENT environment variable or other configuration settings.
Using the Environment Tag Helper helps you keep your views cleaner by eliminating conditional logic from the markup and promoting a clearer separation of concerns. It’s especially valuable when you need to provide different content or behavior based on the context in which your application is running.
Real-Time Example of Environment Tag Helper in ASP.NET Core:
In our ASP.NET Core MVC Web Application, we are using Bootstrap for styling the webpage. For ease of debugging, i.e., on our local development (i.e., Development Environment), we want to load the non-minified bootstrap CSS file, i.e., bootstrap.css.
On the Staging and Production or any other environment except the Development environment, we want to load the minified bootstrap CSS file, i.e., bootstrap.min.css, from a CDN (Content Delivery Network) for better performance. Nowadays, most web applications use CDN to load the minified bootstrap files.
However, if the CDN is down or, for some reason, our application cannot load the file from the CDN, then we want our application to fall back and load the minified bootstrap file (bootstrap.min.css) from our server.
We can achieve this easily using the Environment Tag Helper in the ASP.NET Core MVC Application. But before understanding How to use Environment Tag Helper, let us first understand how we set the environment (i.e., Development, Staging, and Production) in ASP.NET Core Application.
How to Set Environment in ASP.NET Core Application?
To set the Application Environment, i.e., Development, Staging, or Production, we need to use the ASPNETCORE_ENVIRONMENT variable. We can set the value of this ASPNETCORE_ENVIRONMENT variable to Development in the launchsettings.json file, as shown in the image below. You can find the launchsettings.json file within the properties folder of your application.
The other possible values for the ASPNETCORE_ENVIRONMENT variable are Staging and Production. It is also possible to create our environment, which we will discuss in our upcoming article.
Installing Bootstrap in ASP.NET Core MVC Application:
Please install Bootstrap with the wwwroot folder using Library Manager (LibMan). We have already discussed installing BootStrap into our ASP.NET Core Application using Library Manager. So, please read our article on How to install Bootstrap in ASP.NET Core Application.
Modifying _ViewImports.cshtml file:
Please modify the _ViewImports.cshtml file as shown below to include the tag helpers in our application globally. This @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers statement will enable us to use the ASP.NET Core MVC Tag Helpers through all the views of our application.
@using TagHelpersDemo @using TagHelpersDemo.Models @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
ASP.NET Core Environment Tag Helper with Examples:
The Environment Tag Helper in ASP.NET Core supports rendering different content based on the application’s environment. The environment of the application is set by using the ASPNETCORE_ENVIRONMENT variable within the launchsettings.json file with the possible values of either Development, Staging, and Production that we already discussed.
Now, if you want to load the non-minified bootstrap CSS files from your server when the application environment is in Development, then you need to set the environment tag helper as shown below.
Suppose you want to load the minified bootstrap CSS files from the CDN (Content Delivery Network) when the application environment is Staging or Production. In that case, you need to set the environment tag helper as shown below. As you can see, we have specified multiple environments by command separated.
To get the bootstrap CDN link, please visit the following URL.
You will see the following page once you visit the above URL. From here, you need to copy either CSS, JS, or both are per your application requirement. In our example, we only need CSS, so copy the Bootstrap CDN path of CSS only.
Using the Include attribute of the Environment Tag Helper, we can set a single hosting environment name or a comma-separated list of hosting environment names like Staging and Production. Along with the include attribute, we can also use the exclude attribute.
The Exclude attribute is basically used to render the content of the environment tag when the hosting environment does not match the environment specified in the exclude attribute. The following example loads the minified CSS file from the CDN when the application environment is not Development.
What is the use of integrity in CDN Link?
The integrity attribute on the <link> element is used for the SubResource Integrity (SRI in short) Check. The SRI is a security feature that allows a browser to check if the file retrieved from the CDN has been maliciously altered. When the browser downloads the file from the CDN, it regenerates the hash and compares the regenerated hash value against the integrity attribute hash value retrieved from it. If both the hash values match, then only the browser allows the file to be downloaded; otherwise, it is blocked.
What if the CDN is Down?
If the CDN is down or, for some reason, our application cannot reach the CDN, then we want our application to fall back and load the minified bootstrap file (bootstrap.min.css) from our server. Please have a look at the following code.
Explanation of the above Code:
If the environment is “Development”, we are loading the non-minified bootstrap CSS file (i.e., bootstrap.css) from our server. On the other hand, if the application environment is other than “Development”, we are trying to load the minified bootstrap CSS file (i.e., bootstrap.min.css) from the CDN.
Along the same line, we specified a fallback source using the asp-fallback-href attribute. This attribute is used when the CDN is down or, for some reason, if our application cannot reach the CDN. In that case, our application returns and downloads the minified bootstrap file (i.e., bootstrap.min.css) from our server.
We use the following 4 attributes and their associated values to check whether the CDN is down.
- asp-fallback-test-class=”sr-only”
- asp-fallback-test-property=”position”
- asp-fallback-test-value=”absolute”
- asp-suppress-fallback-integrity=”true”
Definitely, there is some processing time involved in calculating the hash and comparing it with the integrity attribute hash value. For most applications, the fallback source is their server. You can turn off the integrity check for the files downloaded from the fallback source by setting the asp-suppress-fallback-integrity attribute to false. Let us understand all the above with Examples.
Modifying the _Layout.cshtml file:
Please modify the _Layout.cshtml file as shown below. Here, we are loading the bootstrap.css files based on the application environment. We also specify the fallback path if the environment is other than Development and the CDN is down. If the Environment is Development, it will load the non-minified bootstrap.css file from our server. If the Environment is other than Development, first, it will try to load the minified bootstrap.min.css file from CDN, and if the CDN is down, it will load the minified bootstrap.min.css file from our server.
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> <environment include="Development"> <link href="~/lib/twitter-bootstrap/css/bootstrap.css" rel="stylesheet" /> </environment> <environment exclude="Development"> <link rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" asp-fallback-href="~/lib/twitter-bootstrap/css/bootstrap.min.css" asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" asp-suppress-fallback-integrity="true" /> </environment> </head> <body> <div class="container"> @RenderBody() </div> </body> </html>
Modifying Home Controller:
Next, modify the Home Controller as shown below. Here, we are simply creating one action method.
using Microsoft.AspNetCore.Mvc; namespace TagHelpersDemo.Controllers { public class HomeController : Controller { public ViewResult Index() { return View(); } } }
Modifying Index.cshtml View:
Next, modify the Index.cshtml view as follows.
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h1>Index View</h1>
Run the application and view the page source code; you should see the following.
As you can see in the above image, the boostrap.css file is loaded from our server, i.e., from wwwroot folder of our application. This makes sense because currently, we set the application environment as Development in the launchsettings.json file. Let us change the environment to Staging and see whether it loads the minified version of the Bootstrap file from CDN or not.
Modify the Environment as Staging:
Open the launchsettings.json file and modify the ASPNETCORE_ENVIRONMENT variable value to staging, as shown below. We are making changes for both IIS Express and Kestrel Web Server.
With the above changes in place, now run the application and view the source. Now, it should show the bootsrap.css file being downloaded from the CDN, as shown below.
Let’s intentionally change the integrity value of the CDN to make sure if the CDN fails; it loads the minified bootstrap.css file from our local server or not. So, add some random value to the value of the integrity attribute of the CDN link. So, modify the _Layout.cshtml file as shown below, and here we are adding abcdef at the end of the integrity property value of the link attribute.
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> <environment include="Development"> <link href="~/lib/twitter-bootstrap/css/bootstrap.css" rel="stylesheet" /> </environment> <environment exclude="Development"> <link rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVMabcdef" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" asp-fallback-href="~/lib/twitter-bootstrap/css/bootstrap.min.css" asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" asp-suppress-fallback-integrity="true" /> </environment> </head> <body> <div class="container"> @RenderBody() </div> </body> </html>
With the above changes in place, now run the application. To confirm whether it is loading Bootstrap from the local server, open the Developer Browser Tool by pressing the F12 key, navigate to the Network, and refresh the page. You should see there are two requests for bootstrap.min.css. This is because the first request is made for CDN, and it gets a 200 success response from CDN, but while matching the integrity value, it failed, and hence it again makes a call to the local server to download the bootstrap.min.css file, which is shown in the below image.
Real-Time Use Cases of EnvironmentTagHelper in ASP.NET Core MVC:
The EnvironmentTagHelper in ASP.NET Core MVC provides a way to render content based on the current hosting environment conditionally. It’s especially useful when you want to include certain scripts, styles, or other HTML elements only in specific environments (e.g., Development, Staging, Production). Using the Environment tag helper, you can streamline the management of environment-specific content in your views. Here are some real-time use cases for EnvironmentTagHelper:
Differentiating CSS & JS between Development and Production:
You might want to use non-minified scripts or styles in a development environment for easier debugging. However, in production, you’d prefer the minified versions for performance.
<environment include="Development"> <link rel="stylesheet" href="~/css/dev-style.css" /> <script src="~/js/dev-script.js"></script> </environment> <environment exclude="Development"> <link rel="stylesheet" href="~/css/style.min.css" /> <script src="~/js/script.min.js"></script> </environment>
Debugging Tools:
If you’re using tools like BrowserSync or any other debugging tools that you don’t want to run in a production environment:
<environment include="Development"> <script src="https://localhost:3000/browser-sync/browser-sync-client.js"></script> </environment>
Environment-Specific Notices:
Display a banner or notice on your site to indicate that you’re in a staging or development environment.
<environment include="Staging"> <div class="staging-banner">This is a staging environment</div> </environment> <environment include="Development"> <div class="dev-banner">This is a development environment</div> </environment>
Loading Mock Data:
You might want to load mock data or use mock services in a development or testing environment.
<environment include="Development"> <script src="~/js/mock-data-service.js"></script> </environment>
Analytics & Tracking Scripts:
You might want to exclude certain tracking scripts, like Google Analytics, from your development or staging environments to prevent data skewing.
<environment exclude="Development,Staging"> <!-- Google Analytics script goes here --> </environment>
Feature Toggles:
You can conditionally display new features only in development or staging environments until they’re ready for production.
<environment include="Development,Staging"> <div class="new-feature">...</div> </environment>
Ensure you’ve configured your environment properly, typically using the ASPNETCORE_ENVIRONMENT variable, to get the desired behavior from this tag helper.
The EnvironmentTagHelper in ASP.NET Core MVC is a built-in Tag Helper that allows you to conditionally render content in your Razor views based on the current hosting environment. This Tag Helper is particularly useful when displaying different content or applying different behaviors depending on whether your application runs in a development, staging, or production environment.
In the next article, I will discuss the Bootstrap Navigation Menu in ASP.NET Core MVC Web Application. Here, in this article, I try to explain Environment Tag Helper in ASP.NET Core MVC Application with Examples. I hope you enjoy this Environment Tag Helper in ASP.NET Core MVC Application article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.