参考
在 ASP.NET Core 中使用多个环境 | Microsoft Learn
.Net Core 多环境的配置、调试和部署 - 朱角 - 博客园 (cnblogs.com)
开发环境
创建配置文件

分别新建配置文件 Prodution
和 Staging
填写内容 ASPNETCORE_ENVIRONMENT
= Prodution
or Staging

新建json文件
复制appsettings.Development.json
两次,分别重命名为appsettings.Production.json
和 appsettings.Staging.json
并且分别新建 Tip
属性,标明当前环境

改写Controller
csharp
[ApiController]
[Route("[controller]/[action]")]
public class WeatherForecastController : ControllerBase
{
private readonly IConfiguration Configuration;
public WeatherForecastController(IConfiguration configuration)
{
Configuration = configuration;
}
[HttpGet]
public ActionResult GetCustomConfig()
{
return Content($@"读取CustomConfig配置为:{Configuration["Tip"]}");
}
}
测试
- 默认情况下读取的是开发环境配置(appsettings.Production.json)


- 切换为
Staging
预览环境

输出正确

- 选择
Production
生产环境

输出正常

项目发布
发布项目
点击发布后选择发布为文件
,然后无脑下一步
修改配置文件
发布后会生成PublishProfiles
文件夹

将子文件复制,并且分别改名为Production.pubxml
和 Staging.pubxml
,
并且分别添加一行 <EnvironmentName>xxxx</EnvironmentName>


指定发布环境
可以在发布前指定环境配置

发布后的环境配置,可以在web.config
中查看

测试
修改Program.cs
代码,这样即使是在生产环境也能使用swagger

生产环境

项目已部署到iis
中,输出正确

预览环境
修改 web.config
文件中 value
的值

刷新swagger页面,输出正确
