Is Development in Razor View

I find myself needing to know if I'm in development from inside a Razor view. In the C# code, you can generally use the #DEBUG preprocessor directive, but it’s not quite so easy in Razor.

I've used an extension method on HtmlHelper to kind of cheat, but the “correct” way seems to be to inject the host environment and call the IsDevelopment method:

@using Microsoft.Extensions.Hosting
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostEnvironment
 
@if (HostEnvironment.IsDevelopment())
{
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true">
}
else
{
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
}
 
@if (HostEnvironment.IsDevelopment())
{
    <script src="~/js/bundle.js" asp-append-version="true"></script>
}
else
{
    <script src="~/js/bundle.min.js" asp-append-version="true"></script>
}

Comments

Popular posts from this blog

C# Record Serialization

Versioned content in MVC

Add timestamp to photo using ImageMagick