新的ASP.NET Core框架使我们能够为不同的环境执行不同的html:
<environment names="Development">
<link rel="stylesheet" href="~/lib/material-design-lite/material.css" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/css/bootstrap.min.css"
asp-fallback-href="~/lib/material-design-lite/material.min.css"
asp-fallback-test-class="hidden" asp-fallback-test-property="visibility" asp-fallback-test-value="hidden"/>
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true"/>
</environment>
但如何确定和可视化ASP.NET Core MVC Web应用程序的_Layout.cshtml
中当前环境的名称?
例如,我想将环境名称(Production,Staging,Dev)可视化为HTML注释,以便进行调试:
<!-- Environment name: @......... -->
答案 0 :(得分:55)
您可以在视图中注入服务IHostingEnvironment
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv
并做一个@hostingEnv.EnvironmentName
答案 1 :(得分:9)
为了验证我刚刚制作了一个简单的API控制器
[Route("api/[controller]")]
public class DebugController : Controller
{
private IHostingEnvironment _hostingEnv;
public DebugController(IHostingEnvironment hostingEnv)
{
_hostingEnv = hostingEnv;
}
[HttpGet("environment")]
public IActionResult Environment()
{
return Ok(_hostingEnv.EnvironmentName);
}
然后我只需运行/api/debug/environment
即可查看该值。
答案 2 :(得分:1)
从.NET Core 3.1开始,建议使用
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment hostingEnv
将此添加到Razor视图的顶部。您可以使用@hostingEnv.EnvironmentName
来获取当前环境。
答案 3 :(得分:0)
.net core 2.2中有以下作品:
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment env
@using Microsoft.AspNetCore.Hosting
if (env.IsProduction())
{
//You can also use:
//env.IsStaging();
//env.IsDevelopment();
//env.IsEnvironment("EnvironmentName");
}