ASP.NET Core 6 Web API部署IIS遇DirectoryNotFoundException的解决方法
解决方案:IIS部署后Resources目录找不到的问题
1. 修正路径获取逻辑(核心问题)
在IIS环境中,Directory.GetCurrentDirectory()返回的是IIS应用程序池的工作目录(通常是C:\Windows\System32\inetsrv或站点临时目录),而非你的项目部署根目录。必须改用IWebHostEnvironment获取正确的内容根路径:
修改Program.cs的静态文件配置:
var builder = WebApplication.CreateBuilder(args); var env = builder.Environment; // ...其他服务配置代码 var app = builder.Build(); app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Resources")), RequestPath = new PathString("/Resources") });
2. 修正服务层的文件保存路径
服务层中硬编码的@"Resources"路径同样依赖错误的工作目录,需要传递正确的根路径:
步骤:
- 在WebApi层的Program.cs中注入内容根路径:
builder.Services.AddScoped(sp => { var env = sp.GetRequiredService<IWebHostEnvironment>(); return env.ContentRootPath; });
- 修改服务类构造函数,注入根路径:
private readonly string _contentRootPath; public YourApprovalService(IUnitOfWork unitOfWork, ILogger<YourApprovalService> logger, IMapper mapper, string contentRootPath) { _unitOfWork = unitOfWork; _logger = logger; _mapper = mapper; _contentRootPath = contentRootPath; }
- 修正文件路径拼接逻辑:
// 替换原硬编码路径 var filePath = Path.Combine(_contentRootPath, "Resources", DateTime.Now.ToString("yymmssfff"), "FileAttachments", attachment.FileName);
3. 验证目录权限与存在性
- 确认部署文件夹(如
E:\myapp)下已创建Resources\FileAttachments目录,路径拼写完全一致(注意大小写统一)。 - 给IIS应用程序池标识授予目录权限:
右键Resources目录 → 属性 → 安全 → 编辑 → 添加,输入IIS AppPool\你的应用池名称,授予读取、写入、修改权限,并确保权限继承到子目录。
4. 修复服务层的空列表问题
注意到服务层中List<IFormFile> attachments = new List<IFormFile>();是一个空列表,会导致文件保存逻辑完全不执行,需替换为从model中获取上传文件:
// 假设ApprovalDto包含Attachments属性存储上传文件 List<IFormFile> attachments = model.Attachments;
5. 验证路径正确性(可选)
在Program.cs中添加日志输出,确认实际使用的路径:
var resourcesPath = Path.Combine(env.ContentRootPath, "Resources"); builder.Logging.LogInformation("Resources目录实际路径: {Path}", resourcesPath);
部署后查看日志,确认路径是否指向你创建的E:\myapp\Resources。
内容的提问来源于stack exchange,提问作者Ayobamilaye
相关产品推荐
相关产品推荐

