您的位置:首页 > 移动开发

Talking appsettings.json in Asp.Net Core

2018-01-15 22:29 543 查看
在ASP.NET Core中,默认提供了三个运行时环境变量,通过查看Hosting源代码我们可以看到,分别是Development、Staging、Production

public static class EnvironmentName
{
public static readonly string Development = "Development";
public static readonly string Staging = "Staging";
public static readonly string Production = "Production";
}


当启动一个ASP.NET Core应用程序时,会确定当前应该运行哪个环境中。默认情况下,如果没有指定环境变量,会自动默认为Production

public class HostingEnvironment : IHostingEnvironment, Extensions.Hosting.IHostingEnvironment
{
public string EnvironmentName { get; set; } = Hosting.EnvironmentName.Production;

public string ApplicationName { get; set; }

public string WebRootPath { get; set; }

public IFileProvider WebRootFileProvider { get; set; }

public string ContentRootPath { get; set; }

public IFileProvider ContentRootFileProvider { get; set; }
}




在新创建的ASP.NET Core Web Application中我们会看到了两个配置文件分别是appsettings.json和appsettings.Development.json。事实上我们还可以添加两个文件分别是appsettings.Staging.json和appsettings.Production.json,分别是预生产环境和生产环境。根据环境变量的名称会加载具体的配置文件。

config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);


可以用面相对象的方式理解这几个文件,appsettings.json作为父类,其他几个文件作为子类,当两个配置文件中定义了同一个节点,会以子类的配置为准,相当于orverwrite。如果对应的配置文件中没有找到节点,会从父类中去查找。



如果我们的应用程序运行在Docker容器中,Docker也允许在Dockerfile中使用ENV指定环境变量

FROM microsoft/aspnetcore:2.0.5
WORKDIR /app
EXPOSE 80
COPY . .
ENV ASPNETCORE_ENVIRONMENT Production
ENTRYPOINT ["dotnet", "WebApplication1.dll"]


还有一种方式是在运行容器的时候使用-e参数

docker run -e ASPNETCORE_ENVIRONMENT=Development -p 5000:5000 <image>:<tag>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐