Friday, November 19, 2021

Using the ASP.NET Core Environment Feature to manage Development vs. Production for any config file type

 ASP.NET Core can understand what "environment" it's running under. For me, that's "development," "test," "staging," "production," but for you it can be whatever makes you happy. By default, ASP.NET understand Development, Staging, and Production.

You can the change how your app behaves by asking "IsDevelopment" to do certain things. For example:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
 
if (env.IsProduction() || env.IsStaging() || env.IsEnvironment("Staging_2"))
{
    app.UseExceptionHandler("/Error");
}

There are helpers for the standard environments, or I can just pass in a string.

You can also make Environmental decisions with taghelpers like this in your Views/Razor Pages. I did this when I dynamically generated my robots.txt files:

@page
@{
    Layout = null;
    this.Response.ContentType = "text/plain";
}
# /robots.txt file for http://www.hanselman.com/
User-agent: *
<environment include="Development,Staging">Disallow: /</environment>
<environment include="Production">Disallow: /blog/private
Disallow: /blog/secret
Disallow: /blog/somethingelse</environment>

This is a really nice way to include things like banners or JavaScript when your site is running in a certain environment. These are easily set as environment variables if you're running in a container. If you're running in an Azure App Service you set the environment from the Config blade:

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...