Environment Tag Helper in ASP.NET Core MVC

Environment Tag Helper in ASP.NET Core MVC Application

In this article, I will discuss the Environment Tag Helper in ASP.NET Core MVC Application with Examples. 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
  2. What is Environment Tag Helper in ASP.NET Core MVC?
  3. How Do We Use the Environment Tag Helper in ASP.NET Core MVC?
  4. How to Set Environment in ASP.NET Core Application?
  5. Real-Time Example of Environment Tag Helper in ASP.NET Core
Different Environments in Software Development:

Software development environments refer to the stages a software product goes through during its development lifecycle. These environments are designed to manage the development process in a structured way, allowing for software testing, development, deployment, and maintenance. 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 is where software developers actively develop and test their code. This is where the actual development of the application takes place. Developers write code, experiment, test features, and debug issues in this environment. This environment is the first step in the development lifecycle, where features are built and initially tested.

  • Who works here: Developers primarily work in this environment. Occasionally, QA engineers can do some testing for specific modules.
  • Features: In the development environment, features are being built or enhanced. This environment contains experimental code, which may be incomplete or unstable. New features are developed, bug fixes are implemented, and code is refactored here.
Developer’s Role:
  • Writing and committing code.
  • Implementing features based on requirements.
  • Running local tests.
  • Debugging and fixing issues.
  • Collaborating with other developers.
Staging Environment

Staging acts as a “pre-production” environment. It’s a clone of the production environment where the application is thoroughly tested before going live. It ensures that everything behaves as expected in a controlled, production-like environment. This environment is crucial for performance testing, security testing, and ensuring the new features work as expected with existing system features in a production-like setting.

  • Who works here: QA testers, product owners, and sometimes even developers perform testing. The business stakeholders may review and approve changes.
  • Features: This environment contains completed features that are ready for final testing. The code deployed here should be close to what will be deployed to production. All integrations (e.g., with third-party services) should also be tested here.
Developer’s Role:
  • Collaborate with QA and testers to resolve any bugs found during testing.
  • Perform bug fixes if necessary.
  • Deploy code to the staging environment for final validation.
Production Environment

This is the live environment where the end users interact with the application. The production environment is the actual operating environment where the final version of the application is hosted and available to customers. It is a highly controlled environment with an emphasis on stability, uptime, and security. The primary focus in production is on monitoring, maintaining system performance, and quickly resolving any issues that impact user experience.

  • Who works here: End-users primarily interact with the production environment. Developers, DevOps engineers, and support teams work to monitor and maintain it. Business teams and product managers review the performance and gather feedback.
  • Features: This environment contains the fully tested and stable version of the application. All features released in production should be fully functional, tested, and verified. Only completed and approved features are pushed to production.
Developer’s Role:
  • Ensure smooth deployment of new features to production.
  • Monitor the application for any post-release issues.
  • Provide hotfixes for critical bugs if necessary.
  • Collaborate with support teams to resolve customer-reported issues.
What is Environment Tag Helper in ASP.NET Core MVC?

The Environment Tag Helper in ASP.NET Core MVC allows developers to conditionally include or render content (such as HTML Blocks, Scripts, or Styles) based on the application’s current environment. That means it allows developers to include or exclude specific blocks of HTML or other Razor content based on whether the app runs in Development, Staging, Production, or any other custom-defined environment.

It uses the ASPNETCORE_ENVIRONMENT environment variable to detect the application’s running environment (e.g., Development, Staging, Production) and adjust the output accordingly. This variable can be set in various places, such as the project properties, launchSettings.json, or directly in the system’s environment variables.

How Do We Use the Environment Tag Helper in ASP.NET Core?

The Environment Tag Helper is used by wrapping the HTML content inside the <environment> tag, specifying which environments the content should be included for. You can specify one or more environments as a comma-separated list. For example,

<environment include="Development">
    <script src="~/js/dev-only-script.js"></script>
</environment>

<environment exclude="Development">
    <script src="~/js/prod-only-script.js"></script>
</environment>

Here:

  • The first <script> tag will be included only when the environment is set to Development. The include attribute specifies the environment names in which the content should be included.
  • The second <script> tag will be included in all environments except Development. The exclude attribute specifies the environment names from which the content should be excluded.
Specifying Multiple Environments:

The include attribute allows you to specify multiple environments using a comma-separated list. If the application runs in any specified environment, the content will be rendered.

<environment include="Development, Staging">
      <!-- Content visible in the Development and Staging environments -->
</environment>
How to Set Environment in ASP.NET Core Application?

The ASPNETCORE_ENVIRONMENT variable sets 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. The other possible values for the ASPNETCORE_ENVIRONMENT variable are Staging and Production

Environment Tag Helper in ASP.NET Core MVC Application

Real-Time Example of Environment Tag Helper in ASP.NET Core:

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.

ASP.NET Core Environment Tag Helper with Examples:

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. We can also use the exclude attribute. The Exclude attribute renders 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 with Exclude Attribute

Understanding the above Code:
  • href: This attribute specifies the URL of the external resource to be linked, which is the Bootstrap 5.3.0 CSS file hosted on 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: This attribute specifies the relationship between the current document and the linked resource. The value “stylesheet” indicates that the linked file is a stylesheet.
  • integrity: This attribute provides a security feature called Subresource Integrity (SRI). It contains a hash value (in this case, using the SHA-384 algorithm) that represents the expected content of the external resource. 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 security feature ensures the resource hasn’t been tampered with.
  • crossorigin: This attribute controls the handling of cross-origin requests. The value “anonymous” indicates that the request for the external resource (in this case, the Bootstrap CSS file) should be made without including credentials (such as cookies, HTTP authentication, or client-side SSL certificates).
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.

Here, 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.NET Core asp-* Attributes:
  • asp-fallback-href: Specifies a fallback URL for the stylesheet if the CDN resource fails to load (for example, due to a network error or CDN downtime). The fallback is a local version of the Bootstrap CSS file located in the project’s /css/ folder.
  • asp-fallback-test-class: Defines a CSS class that the browser will use to determine if the primary CSS file (from the CDN) has loaded correctly. Here, we have used the bootstrap class d-none, and this class will be tested using the property specified by asp-fallback-test-property.
  • asp-fallback-test-property: Specifies the CSS property that will be checked to verify whether the CDN stylesheet is working correctly. In this case, it checks the “display” property of the specified test class (d-none).
  • asp-fallback-test-value: Specifies the expected value of the CSS property (display) for the test class. If the value does not match the expected value (none), the browser will consider the CDN stylesheet to have failed and will load the fallback CSS file.
  • asp-suppress-fallback-integrity: When set to “false”, the integrity check is enforced on the CDN resource. If the integrity check fails (e.g., the hash doesn’t match the file), the fallback will be triggered, and the fallback CSS file will be loaded. This attribute does not apply the integrity check to the fallback CSS file.
Overall Flow

The browser attempts to load the CSS file from the CDN URL specified in the href attribute. Once loaded, it tests whether the class d-none has the display property with a value of none (as defined by the fallback test attributes).

  • If the test passes, the CDN file is successfully loaded, and no fallback occurs.
  • If the test fails (e.g., the CDN file is not loaded, or the class and property are missing), the browser loads the local CSS file specified by asp-fallback-href.
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/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
    </environment>

    <environment exclude="Development">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
              rel="stylesheet"
              integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
              crossorigin="anonymous"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="d-none"
              asp-fallback-test-property="display"
              asp-fallback-test-value="none"
              asp-suppress-fallback-integrity="false">
    </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 to all Launch Profiles.

Setting Environment to Staging in ASP.NET Core

With the above changes, 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 provide some invalid values for the asp-fallback-test-class, asp-fallback-test-property, and asp-fallback-test-value to ensure the integrity check fails and loads the minified bootstrap.css file from our local server. To do this, please modify the _Layout.cshtml file as shown below.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>

    <environment include="Development">
        <link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
    </environment>

    <environment exclude="Development">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
              rel="stylesheet"
              integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
              crossorigin="anonymous"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="d-none1"
              asp-fallback-test-property="display2"
              asp-fallback-test-value="none3"
              asp-suppress-fallback-integrity="false">
    </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 allows us to conditionally render content in 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 *