app.Environment.EnvironmentName
app.Environment.ContentRootPath
app.Environment.IsDevelopment()
app.Environment.IsStaging()
app.Environment.IsProduction()
app.Environment.IsEnvironment("beta")
示例
新建一个ASP.NET Core Empty项目,项目名称EnvironmentsExample
Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
//app.MapGet("/", () => "Hello World!");
app.UseStaticFiles();
app.UseRouting();
app.MapControllers();
app.Run();
新建wwwroot文件夹,添加StyleSheet.cs
新建Controllers/Models/Views/等文件夹
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
<link href="~/stylesheet.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="page-content">
@RenderBody()
</div>
</div>
</body>
</html>
_ViewStart.cshtml
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
HomeController.cs
using Microsoft.AspNetCore.Mvc;
namespace EnvironmentsExample.Controllers
{
public class HomeController : Controller
{
[Route("/")]
[Route("some-route")]
public IActionResult Index()
{
return View();
}
[Route("some-route")]
public IActionResult Other()
{
return View();
}
}
}
Index.cshtml
@{
ViewBag.Title = "Home";
}
<h1>Home</h1>
Program.cs中添加IsDevelopment()
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
//app.MapGet("/", () => "Hello World!");
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.MapControllers();
app.Run();
launchSettings.json中配置环境
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:43938",
"sslPort": 0
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5198",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
设置"ASPNETCORE_ENVIRONMENT": "Development"运行程序后,URL输入http://localhost:5198/some-route显示
设置"ASPNETCORE_ENVIRONMENT": "Staging"运行程序后,URL输入http://localhost:5198/some-route显示
Gitee获取源码: