Environment Tag Helper in ASP.NET Core MVC

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. What is Environment Tag Helper in ASP.NET Core MVC?
  2. Different Environments in Software Development
  3. How Do We Use the Environment Tag Helper in ASP.NET Core MVC?
  4. Real-Time Example of Environment Tag Helper in ASP.NET Core
  5. How to Set Environment in ASP.NET Core Application?
  6. Real-Time Use Cases of Environment Tag Helper in ASP.NET Core MVC
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. That means the Environment Tag Helper is used to include or exclude portions of the Razor view markup based on the current hosting environment. It’s useful for adding or removing links to CSS stylesheets, scripts, or other elements that should only be rendered in specific environments like Development, Staging, or Production. 

Different Environments in Software Development:

Software development environments refer to the stages through which a software product goes during its development lifecycle. These environments are designed to manage the development process in a structured way, allowing for testing, development, deployment, and maintenance of software. Nowadays, most software development organizations typically have the following three environments.

  1. Development Environment
  2. Staging Environment
  3. Production Environment
Development Environment: 

The “Development Environment” refers to a specific stage in the software development lifecycle where developers create and test 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. 

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

  • Who Works Here: Software developers primarily work in this environment. It’s their playground for writing code, developing features, and performing initial unit tests.
  • Responsibilities: Developers are responsible for implementing new features, fixing bugs, and ensuring their code meets initial quality standards before it’s moved to the next environment.
Testing Environment

The Testing Environment is Dedicated to testing and quality assurance. Here, the software is tested for bugs, errors, and issues that weren’t caught during initial development. This Environment Mirrors the production environment as closely as possible to ensure that testing conditions resemble the final usage scenario. This environment may also be referred to as the QA (Quality Assurance) environment.

  • Who Works Here: QA engineers and testers are the primary users of this environment. Their expertise is in systematically finding and reporting bugs, as well as verifying bug fixes.
  • Responsibilities: QA professionals run various tests, including functional tests, regression tests, and sometimes automated tests, to ensure the software meets all requirements and is free of defects.
Staging Environment: 

A “Staging Environment” is a phase in the software development lifecycle that comes after the development/testing 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 need to use the 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 details about the exceptions. Instead, it shows a generic error message like the one below.

“Something went wrong. Our IT team is working to solve this as soon as possible. If you need further details, please Email, Chat, or Call our support team using the contact details below.”

  • Who Works Here: A mix of QA engineers, developers, and sometimes product managers or clients. This environment is a pre-production mirror used for final checks.
  • Responsibilities: Conducting User Acceptance Testing (UAT), performance testing, security testing, and ensuring the software runs as expected in a production-like environment.
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 should 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.

  • Who Works Here: While not a development or testing environment in the traditional sense, operations teams, DevOps, and sometimes developers have roles in managing and monitoring the production environment.
  • Responsibilities: Ensuring the application is running smoothly, deploying new releases, monitoring performance, and quickly addressing any production issues or bugs that arise.
How Do We Use the Environment Tag Helper in ASP.NET Core?

First, ensure your view includes the necessary directive to use Tag Helpers. This is usually already included in _ViewImports.cshtml:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Attributes:
  • include: Specifies the environment names in which the content should be included.
  • exclude: Specifies the environment names from which the content should be excluded. If the current environment matches one of the names in the exclude attribute, the content will not be rendered.

Determining the Current Environment: ASP.NET Core uses the ASPNETCORE_ENVIRONMENT environment variable to determine the current environment. This variable can be set in various places like the project properties, launchSettings.json, or directly in the system’s environment variables.

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>
Real-Time Example of Environment Tag Helper in ASP.NET Core:

In our ASP.NET Core MVC Web Application, we use Bootstrap to style the web page. 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 easily achieve this using the Environment Tag Helper in the ASP.NET Core MVC Application. But before we understand how to use the Environment Tag Helper, let us first understand how we set the environment (i.e., Development, Staging, and Production) in the ASP.NET Core Application.

How to Set Environment in ASP.NET Core Application?

The ASPNETCORE_ENVIRONMENT variable is used to set the Application Environment, i.e., Development, Staging, or Production. As shown below, the launchsettings.json file allows us to set the value of the ASPNETCORE_ENVIRONMENT variable to Development. You can find the launchsettings.json file within your application’s properties folder. 

How to Set Environment in ASP.NET Core 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 globally for our application. This @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers statement will enable us to use the ASP.NET Core MVC Tag Helpers in all of our application’s views.

@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 using the ASPNETCORE_ENVIRONMENT variable within the launchsettings.json file with the possible values of either Development, Staging, and Production, which we have 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.

ASP.NET Core Environment Tag Helper

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 separated by a comma. 

ASP.NET Core Environment Tag Helper Staging and Production

To get the bootstrap CDN link, please visit the following URL.

https://getbootstrap.com/

Once you visit the above URL, you will see the following page. From here, you need to copy either CSS, JS, or both as per your application’s requirements. In our example, we only need CSS, so copy the Bootstrap CDN path of CSS only.

Bootstrap CDN

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 in Development.

Environment Tag Helper in ASP.NET Core MVC

Let’s break down the attributes of the Bootstrap CDN:

  • href=”https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css”: This attribute specifies the URL of the linked document. In this case, it’s pointing to a minified CSS file for Bootstrap version 5.3.0 hosted on the jsDelivr CDN (Content Delivery Network). The min in the filename indicates that it’s a minified version, which means all unnecessary characters like whitespace and comments have been removed to reduce the file size.
  • rel=”stylesheet”: This attribute specifies the relationship between the current document and the linked document. The value “stylesheet” indicates that the linked document is a CSS file and should be treated as a stylesheet.
  • integrity=”sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM”: This attribute provides a way to allow browsers to verify the fetched resource’s integrity. The value is a base64-encoded cryptographic hash (in this case, SHA-384) of the resource’s contents. 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. If both the hash values match, then only the browser allows the file to be downloaded; otherwise, it is blocked. This is a security feature that ensures the resource hasn’t been tampered with.
  • crossorigin=”anonymous”: This attribute is used in conjunction with the CORS (Cross-Origin Resource Sharing) headers of the requested resource. It allows the browser to make cross-origin requests to the jsDelivr CDN without sending credentials like cookies or HTTP authentication. The value “anonymous” means that no user credentials are included in the request to the CDN. This attribute is necessary for the integrity attribute to work properly when requesting resources from a different origin.
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. For a better understanding, please have a look at the following code.

What if the CDN is Down

Explanation of the above Code:

If the environment is “Development,” we load the non-minified bootstrap CSS file (e.g., bootstrap.css) from our server. If the application environment is other than “Development,” we try to load the minified bootstrap CSS file (e.g., bootstrap.min.css) from the CDN.

At the same time, we have also 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.

  • asp-fallback-href=”~/lib/twitter-bootstrap/css/bootstrap.min.css”: This attribute specifies the path to a local copy of the resource to use as a fallback. This attribute is essential for ensuring that your web application can still use Bootstrap even if the CDN is down or inaccessible. The value ~/lib/twitter-bootstrap/css/bootstrap.min.css is the local path within your ASP.NET Core web application where a copy of the Bootstrap CSS file is stored. The tilde ~ symbol represents the root of the web application. So, if the CDN fails to deliver the Bootstrap CSS file, the application will instead load it from the local path specified.

We use the following 3 attributes and their associated values to check whether the CDN is down.

  1. asp-fallback-test-class=”sr-only”
  2. asp-fallback-test-property=”position”
  3. asp-fallback-test-value=”absolute”

asp-fallback-test-class, asp-fallback-test-property, asp-fallback-test-value: These attributes work together to test if the primary CSS file has loaded correctly. ASP.NET Core does this by attempting to apply a style rule (defined by these attributes) and checking if it takes effect. If not, it concludes that the primary resource failed to load and applies the fallback.

asp-suppress-fallback-integrity=”true”: Indicates whether to skip the integrity check for the fallback resource. When set to true, this attribute means that the integrity check (similar to the integrity attribute for external resources) will not be performed on the fallback resource. This is useful when you have complete control over the fallback content and are less concerned about its integrity being compromised (e.g., hosted on your own server).

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.

Setting Environment as Development using Environment Tag Helper

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 we have set the application environment as Development in the launchsettings.json file. Let us change the environment to Staging and see whether or not it loads the minified version of the Bootstrap file from CDN.

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.

Setting Environment to Staging in ASP.NET Core

With the above changes in place, run the application and view the page source code. It should now show the bootsrap.css file being downloaded from the CDN, as shown below.

Using CDN in ASP.NET Core MVC Web Application

Making the CDN Down:

Let’s intentionally change the CDN’s integrity value to ensure that if the CDN fails, it loads the minified bootstrap.css file from our local server. To do this, add some random value to the end of the integrity attribute of the CDN link. Modify the _Layout.cshtml file as shown below, and add 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, 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.

Environment Tag Helper in ASP.NET Core Application with Examples

The Environment Tag Helper 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 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. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *