Asp.net

在 Windows 上使 ASP.NET Core 伺服器 (Kestrel) 區分大小寫

  • April 29, 2019

在 Linux 容器中執行的 ASP.NET Core 應用使用區分大小寫的文件系統,這意味著 CSS 和 JS 文件引用必須區分大小寫。

但是,Windows 文件系統不區分大小寫。因此,在開發過程中,您可以使用不正確的大小寫引用 CSS 和 JS 文件,但它們可以正常工作。因此,在 Windows 上進行開發期間,您不會知道您的應用程序在 Linux 伺服器上執行時會崩潰。

有沒有辦法讓 Windows 上的 Kestrel 區分大小寫,以便我們可以有一致的行為並在上線之前找到參考錯誤?

我在 ASP.NET Core 中使用中間件解決了這個問題。app.UseStaticFiles()而不是我使用的標準:

if (env.IsDevelopment()) app.UseStaticFilesCaseSensitive();
else app.UseStaticFiles();

並將該方法定義為:

/// <summary>
/// Enforces case-correct requests on Windows to make it compatible with Linux.
/// </summary>
public static IApplicationBuilder UseStaticFilesCaseSensitive(this IApplicationBuilder app)
{
   var fileOptions = new StaticFileOptions
   {
       OnPrepareResponse = x =>
       {
           if (!x.File.PhysicalPath.AsFile().Exists()) return;
           var requested = x.Context.Request.Path.Value;
           if (requested.IsEmpty()) return;

           var onDisk = x.File.PhysicalPath.AsFile().GetExactFullName().Replace("\\", "/");
           if (!onDisk.EndsWith(requested))
           {
               throw new Exception("The requested file has incorrect casing and will fail on Linux servers." +
                   Environment.NewLine + "Requested:" + requested + Environment.NewLine +
                   "On disk: " + onDisk.Right(requested.Length));
           }
       }
   };

   return app.UseStaticFiles(fileOptions);
}

它還使用:

public static string GetExactFullName(this FileSystemInfo @this)
{
   var path = @this.FullName;
   if (!File.Exists(path) && !Directory.Exists(path)) return path;

   var asDirectory = new DirectoryInfo(path);
   var parent = asDirectory.Parent;

   if (parent == null) // Drive:
       return asDirectory.Name.ToUpper();

   return Path.Combine(parent.GetExactFullName(), parent.GetFileSystemInfos(asDirectory.Name)[0].Name);
}

引用自:https://stackoverflow.com/questions/50096995