ASP.NET Core / Kestrel 无法一致地提供静态内容

Cli*_*Mug 3 http-status-code-404 razor twitter-bootstrap kestrel-http-server asp.net-core

背景信息:

  • ASP.NET Core v3.1 带 RazorPages
  • 在本地运行良好(本地主机上的 Win10 和 Kestrel)
  • 在部署到 Linux VM (Ubuntu 18) 时, wwwroot/ 中的文件返回 404 ,Bootstrap 在本地工作正常,没有 404
  • 发布方式dotnet publish -r linux-x64
  • 部署的应用程序正在运行 Kestrel 并转发来自 NGINX 的请求。

启动.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    /// Included before other middleware (needed due to nginx forwarding)
    /// Per: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-nginx?view=aspnetcore-3.1
    app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseCookiePolicy(); // -- Added for AaaS?

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        // Added to allow controllers
        endpoints.MapControllers();

        // Original Razor Page way
        endpoints.MapRazorPages();
    });

}
Run Code Online (Sandbox Code Playgroud)

_布局_.cshtml

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - Title</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</head>
Run Code Online (Sandbox Code Playgroud)

wwwroot/ 的部分布局

  • CSS/
    • 站点.css
  • js/
    • 站点.js
  • 库/
    • 引导程序/
      • 距离/
      • CSS/
        • 引导程序.css
    • jquery/

Cli*_*Mug 5

解决。

事实证明,我没有注意运行时我所在的目录dotnet aspSample.dll。这样做的结果是我的“内容根路径”会根据我执行该命令时所在的位置而改变。为了解决这个问题,我必须确保我位于 Ubuntu VM 上的正确目录/publish/中,然后运行dotnet aspSample.dll以确保设置Content root path: /var/www/aspSample/publish正确

在查看了这篇文章中未接受的答案后:Asp.Net Core 2.0-2.2 Kestrel not services static content我看到了我的答案,但描述得更好,因此下面引用了它。

对我来说,问题在于工作目录。尝试使用 dotnet /var/www/project/project.dll 启动应用程序时,我没有注意所在的目录。当您以这种方式启动应用程序时,它会自动使用您的当前目录作为工作目录。

当我查看另一个项目的 .service 文件时,我意识到了这一点,该文件指定了工作目录:

...
WorkingDirectory=/var/www/project/
ExecStart=/usr/bin/dotnet /var/www/project/project.dll
...
Run Code Online (Sandbox Code Playgroud)

因此,请确保运行项目时位于正确的目录中,或者确保在 .service 文件中正确设置了工作目录。