Search code examples
c#asp.net.netasp.net-coreblazor

How to add an environment indicator into a razor page?


I wish to add something to a razor page so that when I inspect the page code behind, I'm able to tell if it is in Production, Staging, or Development mode. In this case, I'm adding a hidden field to tell me what mode the page is in. It is not the cleanest looking code. Any ideas on a different approach to insert a status water mark of sorts into the rendered code?

@if (Env.IsProduction()) {
    <input type="hidden" name="EnvironmentName" id="EnvironmentName" value="Production" />
}
@if (Env.IsStaging())
{
    <input type="hidden" name="EnvironmentName" id="EnvironmentName" value="Staging" />
}
@if (Env.IsDevelopment())
{
    <input type="hidden" name="EnvironmentName" id="EnvironmentName" value="Development" />
}

The code behind currently looks like this:

enter image description here


Solution

  • I mean, you can do whatever you like, basically? Here’s an example that just displays the title of the current Hosting Environment by injecting IWebHostEnvironment right into the Razor page:

    @page
    @model MyApp.IndexModel
    @inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment Env
    
    <h1>@Env.EnvironmentName</h1>
    

    That’s pretty much how it’s done in this sample from the docs: https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/environments/samples/6.x/EnvironmentsSample/Pages/About.cshtml