How do I access the HostingEnvironment within a layout in Razor Pages ASP.NET Core?

Viewed 362

So the end goal is that I want within the dashboard to highlight what database servers are connected to based on the connection strings in appsettings.json. I have that working but only for the main appsettings.json, whereas I want to know what is in play when considering appsettings.Development.json and appsettings.Production.json.

In order to do this, I need a means of accessing the HostingEnvironment, but I can't seem to find a means to expose it in the layout.

var env = Context.HostingEnvironment; // this is the part I need to fix, everything else works.
var configuration = new ConfigurationBuilder()
      .AddJsonFile("appsettings.json")
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
      .Build();
var sqlBuilder = new SqlConnectionStringBuilder();

sqlBuilder = new SqlConnectionStringBuilder(configuration.GetConnectionString("DB1Connection"));
ViewData["DB1"] = sqlBuilder.DataSource;
sqlBuilder = new SqlConnectionStringBuilder(configuration.GetConnectionString("DB2Connection"));
ViewData["DB2"] = sqlBuilder.DataSource;
sqlBuilder = new SqlConnectionStringBuilder(configuration.GetConnectionString("DB3Connection"));
ViewData["DB3"] = sqlBuilder.DataSource;
1 Answers

Use the @inject directive to inject an instance of it:

@inject IWebHostEnvironment environment
<!DOCTYPE html>
<html>
<head>...

Then you can use it later:

@if(environment.IsDevelopment())
{
    ...
}

You will need to add a couple of using directives to the top-level _ViewImports file:

@using Microsoft.AspNetCore.Hosting
@using Microsoft.Extensions.Hosting

See here for more info on injecting into views and layouts: https://www.learnrazorpages.com/advanced/dependency-injection#injecting-into-content-pages-or-views

Related