【Azure App Service】.NET应用读取静态文件时遇见了404错误的解决方法 - LuBu0505/My-Code GitHub Wiki

问题描述

使用.NET 8开发应用,部署到Azure App Service后,需要直接访问一些静态图片/视频文件,但是直接通过相对路径获取文件时,遇见404错误........ image.png

问题解答

在网上搜索“.NET应用读取静态文件”关键字,找到了问题原因。在IIS部署应用时代(.NET Core之前),是通过IIS服务来匹配文件路径,所以可以通过进入根目录后的文件夹路径找到静态文件(如css,font,js, 图片和视频等文件)。

但是,在.NET Core时代,需要使用 app.UseStaticFiles() 中间件实现。并且文件路径为。 默认目录为 {content root}/wwwroot。如果文件路径不在wwwroot目录中。可以通过UseStaticFiles方法指定并修改。例如:

app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Images")),
    RequestPath = new PathString("/Images")
});

StaticFileOptions的属性介绍:静态文件的实际路径为当前根目录下的Images文件夹,当通过URL请求图片时,通过根路径‘/’后的images来映射到真实文件夹Images中。

       //
        // Summary: // The relative request path that maps to static resources. This defaults to the site root '/'.
        public PathString RequestPath { get; set; } //
        // Summary: // The file system used to locate resources //
        // Remarks: // Files are served from the path specified in Microsoft.AspNetCore.Hosting.IWebHostEnvironment.WebRootPath // or Microsoft.AspNetCore.Hosting.IWebHostEnvironment.WebRootFileProvider which // defaults to the 'wwwroot' subfolder.
        public IFileProvider? FileProvider { get; set; }

当把 UseStaticFiles 添加后,部署到App Service后,直接访问静态图片路径,成功返回图片。 image.png

参考资料

ASP.NET Core 中的静态文件 : https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/static-files?view=aspnetcore-8.0

当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!