晚了,但我认为我的解决方案会对其他人有所帮助。
步骤 1. 将 appseting 放入文件夹“Settings/appsettings.json”。
这是我的 appsettings.json
{
"ConnectionString": "Data Source=local;Initial Catalog=mydb;User Id=username;Password=myStr0ngPassword@;"
}
第 2 步。从 asp netcore 编辑代码。
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
namespace Repos.Configs
{
public static class ConfigurationManager
{
public static string currentPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
public static IConfiguration AppSetting { get; }
static ConfigurationManager()
{
AppSetting = new ConfigurationBuilder()
.SetBasePath(currentPath)
.AddJsonFile("Settings/appsettings.json") // your path here
.Build();
}
}
}
并使用 AppSetting。
var connectionString = ConfigurationManager.AppSetting["ConnectionString"];
第 3 步。现在你必须配置你的 dockerfile,在我的例子中,由 Visual Studio 在 linux 容器中创建。
FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build
WORKDIR /src
COPY ["Api/Api.csproj", "Api/"]
COPY ["Repos/Repos.csproj", "Repos/"]
COPY ["DataContext/DataContext.csproj", "DataContext/"]
RUN dotnet restore "Api/Api.csproj"
COPY . .
WORKDIR "/src/Api"
RUN dotnet build "Api.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "Api.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Api.dll"]
第 4 步。构建映像。
docker build -t tagForProject .
第 5 步。映射卷并从映像运行您的容器。
docker run -p 44382:80 --volume c:\Docker\Volumes\MyProjectNetCore:/app/Settings --name nameWillDisplayInDockerDashboard -d tagForProject
好的,这里有一个问题,因为 docker 会将 c:\Docker\Volumes\MyProjectNetCore 覆盖到 /app/Settings。所以,你必须把 appseting.json 放到 c:\Docker\Volumes\MyProjectNetCore。
如果没有,您的应用无法读取 appsetting,因为它不存在于 docker 卷中。
第 6 步。在 docker 仪表板中重新启动您的应用并查看它是否正常工作。