.NET Core应用启动报错:缺失wwwroot目录引发DirectoryNotFoundException
解决.NET Core应用启动时
DirectoryNotFoundException找不到wwwroot目录的问题 问题详情
运行.NET Core应用时抛出异常:
错误信息:System.IO.DirectoryNotFoundException: 'C:####\wwwroot'
报错代码位于Program.cs的WebApplication.CreateBuilder(args)行:
public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args);//报错行 }
当前项目的launchsettings.json配置如下:
{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:10598", "sslPort": 0 } }, "profiles": { "WebAutomation": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "applicationUrl": "http://localhost:5206", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
解决方案
- 创建wwwroot目录:直接在项目根目录新建空的
wwwroot文件夹。ASP.NET Core默认将此目录作为静态文件根目录,启动时会自动检测,即使目录为空也不会报错。 - 配置正确的工作目录:如果项目结构特殊,在launchsettings.json的对应profile中添加
workingDirectory字段,指定项目根目录的绝对路径,示例:"WebAutomation": { // 原有配置... "workingDirectory": "D:\\Projects\\YourWebProject" } - 调整项目文件配置:打开项目的.csproj文件,若不需要静态文件支持,可添加配置关闭默认的wwwroot查找:
<PropertyGroup> <DisableStaticFiles>true</DisableStaticFiles> </PropertyGroup> - 清理重建项目:执行以下命令清理缓存并重新构建项目:
dotnet clean dotnet build
内容的提问来源于stack exchange,提问作者dotnetdev1
相关产品推荐
相关产品推荐

