Docker找不到wwwroot文件。

3

这是我第一次尝试在我的 asp.net core 5.0 应用程序中运行 docker 镜像。我在 Dockerfile 中添加了以下配置。

FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["Shopping.Client/Shopping.Client.csproj", "Shopping.Client/"]
RUN dotnet restore "Shopping.Client/Shopping.Client.csproj"
COPY . .
WORKDIR "/src/Shopping.Client"
RUN dotnet build "Shopping.Client.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Shopping.Client.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Shopping.Client.dll"]

我正在尝试使用以下代码访问位于我的 wwwroot 文件夹中的文件:
private async Task<T> ReadAsync<T>(string filePath)
{

    using FileStream stream = File.OpenRead(filePath);
    return await JsonSerializer.DeserializeAsync<T>(stream);
}

public async Task<List<Product>> GetProducts()
{
    var filePath = System.IO.Path.Combine(_env.ContentRootPath, @"wwwroot\Db\product.json");
    return await ReadAsync<List<Product>>(filePath);
}

当我运行应用程序并尝试访问wwwroot中的文件时,出现以下错误:

执行请求时发生未处理异常。
System.IO.FileNotFoundException: 找不到文件 “/app/wwwroot/Db\product.json”。 文件名: “/app/wwwroot/Db\product.json”

我是否需要在docker文件中包含任何特殊内容以复制wwwroot文件夹,或者我需要考虑docker镜像中的文件路径添加文件路径?


我通过在VS中进行调试来运行应用程序。我没有单独运行docker命令。 - Aakash Bashyal
2
正如答案所说,你可以尝试使用 /,因为它也适用于Windows系统。 - Lei Yang
1
是的,我把路径改成了wwwroot/Db/product.json,现在可以正常运行了。 - Aakash Bashyal
2个回答

6

您正在使用Linux容器并使用Windows文件路径约定。 Path.Combine 支持此功能,但需要一些帮助。

/app/wwwroot/Db\product.json

尝试使用 wwwroot/Db/product.json

如果这是您的问题,您可能希望检查 Path.Combine 的重载,因为 Combine 方法具有接受其他参数的附加重载。

  1. public static string Combine(string path1, string path2, string path3)
  2. public static string Combine(string path1, string path2, string path3, string path4)
  3. public static string Combine(params string[] paths)

您的代码: Path.Combine(_env.ContentRootPath, @"wwwroot\Db\product.json");

然后变成类似于以下内容: Path.Combine(basePath, "wwwroot", "Db", "product.json");


0
请尝试使用Try..Catch语句块。 例如:
public async Task<List<Product>> GetProducts()
{
  try 
  {
      var filePath ="wwwroot//Db//product.json";
    return await ReadAsync<List<Product>>(filePath);
  }
  catch (Exception e)
  {
    //  Block of code to handle errors
  return List<Product>();
  }

}

关于运行容器,您可以使用以下命令:

使用卷: 您可以在此路径(在窗口上)查看卷列表:

\wsl.localhost\docker-desktop-data\data\docker\volumes

> docker run -v volumeName:/app/wwwroot/Db -p 7778:80 imagename 

或者你可以使用挂载路径:(不建议) 例如,你想保存在 c:\Db

> docker run -v c:/db:/app/wwwroot/Db -p 7778:80 imagename 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接