IHostingEnviroment 获取环境相关洗洗
IsDevelopment()、IsStaging()、IsProduction() 分别为:开发、准生产、生产环境
IsEnviroment("Uat") 自定义环境,比如自定义Uat环境
新建:
appsettings.Uat.json文件
{"Enviroment": "Uat"}
Controller文件:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Configuration;namespace WebApplication1.Controllers{[Route("[Controller]")]public class EnviromentController : Controller{private readonly IConfiguration _configuration;public EnviromentController(IConfiguration configuration){_configuration = configuration;}[HttpGet("Index")]public IActionResult Index(){String enviroment=_configuration["Enviroment"];return View(nameof(Index), enviroment);}}}
view文件:
@model string@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment hostEnvi@{Layout = null;}<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>Index</title></head><body><h1>@hostEnvi.EnvironmentName</h1><h1>@Model</h1></body></html>
在launchSettings.json文件profiles下中添加:
"Uat": {"commandName": "Project","launchBrowser": true,"applicationUrl": "http://localhost:5000","environmentVariables": {"ASPNETCORE_ENVIRONMENT": "Uat"}}
选择Uat运行
结果: