新的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: @......... -->
您可以通过执行操作在视图中注入服务IHostingEnvironment
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv
并做一个@hostingEnv.EnvironmentName
为了验证我刚刚制作了一个简单的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
来查看值。
以下工作在.net核心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");
}