Reputation: 225
I am trying to display the version, build date and environment variable on the NavMenu of a Blazor Webassembly application. Here is what i have tried but in vain
NavMenu.razor.cs
protected static Version AppVersion => Assembly.GetExecutingAssembly().GetName().Version?? throw new NullReferenceException();
protected DateTime BuildDate => new DateTime(2000, 1, 1).AddDays(AppVersion.Build).AddSeconds(AppVersion.Revision * 2);
protected string DisplayEnvironment => Environment.GetEnvironmentVariable(EnvironmentVariableTarget.Process) ?? throw new NullReferenceException()
When i run the app i get null reference exception possibly on DisplayEnvironment property. I would appreciate any help.
Upvotes: 1
Views: 2315
Reputation: 5164
According to this link, environment variables aren't available to Blazor WebAssembly.
You can obtain the app's environment in a component by injecting IWebAssemblyHostEnvironment and reading the Environment property.
@using Microsoft.AspNetCore.Components.WebAssembly.Hosting
@inject IWebAssemblyHostEnvironment HostEnvironment
<h1>Environment example</h1>
<p>Environment: @HostEnvironment.Environment</p>
Reference link: ASP.NET Core Blazor environments
Update:
Version:
protected static Version AppVersion => System.Reflection.Assembly.GetExecutingAssembly().GetName().Version ?? throw new NullReferenceException();
Build Date:
You can add the AssemblyTitle (or any other attribute you like) to your csproj file:
<PropertyGroup>
<AssemblyTitle>$([System.DateTime]::Now)</AssemblyTitle>
</PropertyGroup>
If you want to format the date, you can do like this:
<AssemblyTitle>$([System.DateTime]::Now.ToString(yyyyMMdd-HHmm))</AssemblyTitle>
Then in your Blazor code:
string BuildInfo;
protected override void OnInitialized()
{
Assembly curAssembly = typeof(Program).Assembly;
BuildInfo = $"{curAssembly.GetCustomAttributes(false).OfType<AssemblyTitleAttribute>().FirstOrDefault().Title}";
}
Upvotes: 5