In this blog post, we will demonstrate how to print environment variables in an ASP.NET Razor Page.
In our previous blog post on ASP.NET, we demonstrated how to manage environment-specific settings in ASP.NET Core. We achieved this by configuring variables within an environment-specific file.
In this post, we will print an environment-specific variable called MyApp to an ASP.NET Razor page.
Configuration
In the example below, I have configured my Razor Page Model with two properties: Greeting and Connectionstring. These properties hold and display data on the Razor page.
IndexModel.cshtml.cs (Page Model)
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
public class IndexModel : PageModel
{
private readonly IConfiguration _configuration;
// Properties to hold the data you want to display
public string Greeting { get; private set; }
public string ConnectionString { get; private set; }
public IndexModel(IConfiguration configuration)
{
_configuration = configuration;
}
public void OnGet()
{
Greeting = "Hello, welcome to our application!";
ConnectionString = _configuration.GetConnectionString("MyApp");
}
}
The Razor page below displays the Greeting property model using the @model syntax which gives us access to the properties of the model.
Index.cshtml (Razor View)
@page
@model IndexModel
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>@Model.Greeting</h1>
<p>The current connection string is: @Model.ConnectionString</p>
</body>
</html>