简体   繁体   English

如何解决 asp.net core mvc 项目中的“未找到视图”异常

[英]How do I solve a "view not found" exception in asp.net core mvc project

I'm trying to create a ASP.NET Core MVC test app running on OSX using VS Code.我正在尝试使用 VS Code 创建一个在 OSX 上运行的 ASP.NET Core MVC 测试应用程序。 I'm getting a 'view not found' exception when accessing the default Home/index (or any other views I tried).访问默认主页/索引(或我尝试过的任何其他视图)时,我收到“未找到视图”异常。

This is the Startup configuration这是启动配置

    public void Configure(IApplicationBuilder app) {

        // use for development
        app.UseDeveloperExceptionPage();
        app.UseDefaultFiles();
        app.UseStaticFiles();

        app.UseMvc( routes => {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}"
            );
        });
    }

And I have the view defined in Views/Home/index.cshtml , and I have the following packages included on project.json我在Views/Home/index.cshtml中定义了视图,并且我在 project.json 中包含以下包

"dependencies": {
"Microsoft.NETCore.App": {
  "version": "1.0.0-rc2-3002702",
  "type": "platform"
},
"Microsoft.AspNetCore.Razor.Tools" : "1.0.0-preview1-final",
"Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
"Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Routing": "1.0.0-rc2-final"
},

And finally, this is the exception I get.最后,这是我得到的例外。

System.InvalidOperationException: The view 'Index' was not found. The following locations were searched:
    /Views/Home/Index.cshtml
    /Views/Shared/Index.cshtml
    at Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable`1 originalLocations)
    at Microsoft.AspNetCore.Mvc.ViewResult.<ExecuteResultAsync>d__26.MoveNext()
    --- End of stack trace from previous location where exception was thrown --- ...

Any suggestions of what I might be missing ?关于我可能遗漏的任何建议?

In my case, the build action was somehow changed to Embedded resource which is not included in published files.就我而言,构建操作以某种方式更改为未包含在已发布文件中的嵌入式资源

Changing Embedded resource to Content resolves my issue.Embedded resource更改为Content解决了我的问题。

在此处输入图像描述

I found this missing piece.我找到了这个缺失的部分。 I ended up creating a ASP.NET Core project in VS2015 and then compare for differences.我最终在 VS2015 中创建了一个 ASP.NET Core 项目,然后比较差异。 It turns out I was missing .UseContentRoot(Directory.GetCurrentDirectory()) from WebHostBuilder in main.事实证明,我在主要的WebHostBuilder中缺少.UseContentRoot(Directory.GetCurrentDirectory())

After adding this:添加后:

public static void Main(string[] args)
{
    new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .Build()
        .Run();
}

I then got an exception regarding missing preserveCompilationContext .然后我得到了一个关于缺少preserveCompilationContext的异常。 Once added in project.json my view shows correct.在 project.json 添加后,我的视图显示正确。

"buildOptions": {
    "preserveCompilationContext": true,
    "emitEntryPoint": true
},

Check your .csproj file.检查您的 .csproj 文件。 Make sure your file(s) are not listed like:确保您的文件未列出如下:

<ItemGroup>
   <Content Remove="Views\Extractor\Insert.cshtml" />
   <Content Remove="Views\_ViewImports.cshtml" />
</ItemGroup>

If it is listed like above, remove the ones you need.如果它像上面一样列出,请删除您需要的那些。 Sometimes, that happens when we do right click and change build setting to Compile.有时,当我们右键单击并将构建设置更改为编译时会发生这种情况。

I just upgraded from .net core 2.2 to 3. Two ways to resolve I found:我刚刚从 .net core 2.2 升级到 3。我发现了两种解决方法:

Either call AddRazorRuntimeCompilation() when configuring mvc, like:在配置 mvc 时调用AddRazorRuntimeCompilation() ,例如:

services.AddControllersWithViews()
    .AddRazorRuntimeCompilation(...);

more info here: https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#opt-in-to-runtime-compilation更多信息在这里: https ://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#opt-in-to-runtime-compilation

Or remove the following lines from the .csproj:或者从 .csproj 中删除以下行:

<RazorCompileOnBuild>false</RazorCompileOnBuild>
<RazorCompileOnPublish>false</RazorCompileOnPublish>

I have to add in project.json this:我必须在 project.json 中添加这个:

"publishOptions": {
    "include": [
        "wwwroot",
        "**/*.cshtml",
        "appsettings.json",
        "web.config"
    ]
},

The solution of my project was by我的项目的解决方案是
1- Adding AddRazorRuntimeCompilation() such as services.AddControllersWithViews().AddRazorRuntimeCompilation(); 1- 添加 AddRazorRuntimeCompilation() 例如services.AddControllersWithViews().AddRazorRuntimeCompilation(); into StartUp ConfigureServices .进入StartUp ConfigureServices

2- and Keeping this <RazorCompileOnBuild>false</RazorCompileOnBuild> 2-并保持这个<RazorCompileOnBuild>false</RazorCompileOnBuild>

in .csproj ..csproj中。 Then Build the project.然后构建项目。

Updated更新

Make sure you have this NuGet package added to your project:确保您已将此 NuGet 包添加到您的项目中:

Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

For anyone struggling with this, I had a different problem than all the above.对于任何为此苦苦挣扎的人,我遇到的问题与上述所有问题不同。 My local version worked fine, but the live production version gave this error.我的本地版本运行良好,但现场制作版本出现此错误。 It turned out the Unix filenames were different from the ones showing in Windows.事实证明,Unix 文件名与 Windows 中显示的文件名不同。

Git has a nasty setting that's enabled by default: core.ignorecasegit ( you can check this setting on the commandline with config --get core.ignorecase ) Git 有一个默认启用的讨厌设置:core.ignorecasegit(您可以在命令行上使用config --get core.ignorecase检查此设置)

The solution was to rename the files to something else (eg xxx.cs ), commit and push, then rename them back to original with the correct casing/capitalization and commit and push again.解决方案是将文件重命名为其他文件(例如 xxx.cs ),提交并推送,然后使用正确的大小写/大写将它们重命名为原始文件,然后再次提交并推送。

I am using VS2017.我正在使用 VS2017。 In my case there was the view file at the proper place (with the proper name).就我而言,视图文件位于正确的位置(具有正确的名称)。 Then I remembered that I renamed it before, (and the VS somehow did not asked me if I wanna change all the references as usual).然后我记得我之前重命名了它,(并且 VS 不知何故没有问我是否想像往常一样更改所有引用)。 So I finally deleted the view, then I made it again, and this solved my problem.所以我终于删除了视图,然后我又做了一次,这解决了我的问题。

I had the same problem in ASP.Net Core MVC (.Net 6).我在 ASP.Net Core MVC (.Net 6) 中遇到了同样的问题。 I simply updated my Visual Studio 2022 to the latest version which is 17.1.0 and that solved the error.我只是将我的 Visual Studio 2022 更新到最新版本 17.1.0 并解决了错误。

I had this same issue while building an Identity Server instance, everything worked great if I ran the project from Visual Studio but after publishing the project and running with the dotnet command I got the "View not found" error when Identity Server tried to serve up the Login view.我在构建 Identity Server 实例时遇到了同样的问题,如果我从 Visual Studio 运行项目,一切都很好,但是在发布项目并使用dotnet命令运行后,当 Identity Server 尝试提供服务时,出现“找不到查看”错误登录视图。 I already had verified everything else mentioned here but it still wasn't working.我已经验证了这里提到的所有其他内容,但它仍然无法正常工作。 I finally found that the problem was with how I Was running the dotnet command.我终于发现问题出在我运行dotnet命令的方式上。 I was running it from the parent folder, one level above my Identity Server instance and this affected the content root path, for example, running this:我从父文件夹运行它,比我的 Identity Server 实例高一级,这影响了内容根路径,例如,运行这个:

dotnet myWebFolder/MyIdentityServer.dll

gave me the following output when Identity Server started: Identity Server 启动时给了我以下输出:

显示内容根路径设置为 C:\inetpub\aspnetcore 的输出日志

So, the full path of my dll in this case is C:\inetpub\aspnetcore\myWebFolder\MyIdentityServer.dll and I ran the dotnet command from the C:\inetpub\aspnetcore\ folder.因此,在这种情况下,我的 dll 的完整路径是C:\inetpub\aspnetcore\myWebFolder\MyIdentityServer.dll ,我从C:\inetpub\aspnetcore\文件夹运行dotnet命令。

To get the correct content root I had to make sure I ran the dotnet command from the same folder where the dll is, as in dotnet MyIdentityServer.dll .为了获得正确的内容根目录,我必须确保从 dll 所在的同一文件夹中运行dotnet命令,如dotnet MyIdentityServer.dll That change gave me this output:这种变化给了我这个输出:

显示内容根路径设置为 C:\inetpub\aspnetcore\myWebFolder 的输出日志

Now my content root path is correct and Identity Server finds the Login views at C:\inetpub\aspnetcore\myWebFolder\Views\Account\Login.cshtml现在我的内容根路径是正确的,Identity Server 在C:\inetpub\aspnetcore\myWebFolder\Views\Account\Login.cshtml找到登录视图

Visual Code With dotnet version 2.2.300 gave an error message, so not a runtime exception.使用 dotnet 版本 2.2.300 的可视代码给出了错误消息,因此不是运行时异常。

My controller was derived from ControllerBase instead of Controller.我的控制器是从 ControllerBase 而不是 Controller 派生的。 So, I had to change ControllerBase to Controller.因此,我不得不将 ControllerBase 更改为 Controller。

if you are porting your project from a console app to a web app, you need to change this line in your .csproj file如果要将项目从控制台应用程序移植到 Web 应用程序,则需要在.csproj文件中更改此行

from:从:

<Project Sdk="Microsoft.NET.Sdk">

to:至:

<Project Sdk="Microsoft.NET.Sdk.Web">

Same issue started happening for me after we migrated from .net 2.2 to 6. Locally it was fine but only deployed version was giving The view 'Index' was not found error.在我们从 .net 2.2 迁移到 6 后,同样的问题开始发生在我身上。在本地它很好,但只有部署的版本给出了The view 'Index' was not found错误。

It turns out windows-latest and latest visual studio in build pipeline wasn't actually mean windows 2022 and visual studio 2022 YET.事实证明,构建管道中的windows-latestlatest visual studio 实际上并不意味着 windows 2022 和 visual studio 2022 YET。 And therefore published version wasn't supporting .net 6.因此发布的版本不支持 .net 6。

After specifying 2022 versions for both windows and visual studio it started working.在为 Windows 和 Visual Studio 指定 2022 版本后,它开始工作。

Here is the reference: https://github.com/dotnet/core/issues/6907这是参考: https ://github.com/dotnet/core/issues/6907

FWIW, In our case we received this error when accessing localhost:<port>/graphql even though the View/GraphQL/Index.cshtml was in the right place. FWIW,在我们的例子中,我们在访问localhost:<port>/graphql时收到了这个错误,即使View/GraphQL/Index.cshtml位于正确的位置。 We got the error because wwwroot/bundle.js and wwwroot/style.js was mistakenly not initially committed, since our .gitignore included wwwroot .我们收到错误是因为wwwroot/bundle.jswwwroot/style.js最初没有被错误地提交,因为我们的.gitignore包含wwwroot Discovered it by inspecting the network traffic and seeing it was these files giving the 404 and not the Index.cshtml itself.通过检查网络流量发现了它,发现是这些文件给出了 404 而不是Index.cshtml本身。

Im my case it simply was a "forget" error...我的情况是,这只是一个“忘记”错误......
I had the folder with view not named the same as the controller name.我的文件夹视图与控制器名称不同。
Renamed the folder to the correct name.. and works...将文件夹重命名为正确的名称......并且工作......

I also got similar error.我也遇到了类似的错误。 I am using .Net Core 6.0 ASP .Net MVC project.我正在使用 .Net Core 6.0 ASP .Net MVC 项目。

It was resolved just by adding following in the program.cs只需在 program.cs 中添加以下内容即可解决

builder.Services.AddRazorPages().AddRazorRuntimeCompilation();

You will need to add following package reference in project file您需要在项目文件中添加以下包引用

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.3" />
</ItemGroup>

Reply to @LukaszDev (dont think I can attach images to a comment) My view is I ndex.cshtml, typo from my side.回复@LukaszDev(不要认为我可以将图像附加到评论中)我的观点是的 ndex.cshtml,我这边的错字。 See attached screenshot见附件截图

在此处输入图像描述

My controller is as simple as can be.我的控制器尽可能简单。 I get same error for both Index and Welcome Index 和 Welcome 都出现同样的错误

using Microsoft.AspNetCore.Mvc;

namespace app1 {

    [Route("[controller]")]
    public class HomeController : Controller {

        // default action, configured in Startup.cs route
        public IActionResult Index() {
            // handles route /home
            return View();
        }

        [Route("welcome")]
        public IActionResult WelcomeActionDoesNotHaveToMatchName() {
            // handles router /home/welcome
            return View("Welcome"); 
        }
    }
}

就我而言,问题来自我在 csproj 中设置的<EnableDefaultContentItems>false</EnableDefaultContentItems>

In case of someone has a similar problem.如果有人有类似的问题。 It turned out that my csproj file has a few invalid references to my view.事实证明,我的 csproj 文件对我的视图有一些无效的引用。 I deleted any record related to my view, I removed the csproj.user file from the project directory and I reloaded the project, then I included my view.我删除了与我的视图相关的所有记录,我从项目目录中删除了 csproj.user 文件并重新加载了项目,然后我包含了我的视图。 things started working.事情开始起作用了。

I had the same problem under Arch Linux, Visual Studio Code and .NET Core 3.1 and 5.0.我在 Arch Linux、Visual Studio Code 和 .NET Core 3.1 和 5.0 下遇到了同样的问题。

I solved it by removeing the path to the csproj-file in the build section of the tasks.json file:我通过在tasks.json文件的构建部分中删除 csproj 文件的路径来解决它:

"tasks": [
    {
        "label": "build",
        "command": "dotnet",
        "type": "process",
        "args": [
            "build",
            // removed the following line:
            // "${workspaceFolder}/ProjectFoo.csproj",
            "/property:GenerateFullPaths=true",
            "/consoleloggerparameters:NoSummary"
        ],
        "problemMatcher": "$msCompile"
    },

In my case after migrating from Core 2.2 to 3.1 my static html file was not being found.在我从 Core 2.2 迁移到 3.1 之后,我的静态 html 文件没有找到。 In my startup.cs file I had to add app.UseDefaultFiles() just before app.UseStaticFiles() to make it work.在我的 startup.cs 文件中,我必须在app.UseDefaultFiles() app.UseStaticFiles()才能使其工作。 So something like this:所以是这样的:

public void ConfigureServices(IServiceCollection services)
{
   .
   .
   .
   services.AddControllersWithViews();
   .
   .
   .
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
   .
   .
   .
   app.UseDefaultFiles();
   app.UseStaticFiles();
   app.UseRouting();
   .
   .
   .
   app.UseEndpoints(endpoints =>
   {
          endpoints.MapControllerRoute(
          name: "default",
          pattern: "{controller=Home}/{action=Index}/{id?}");
   });
}

I had this error on Ubuntu Linux and was trying to run it from the CLI for the first time, so I fixed it by running the dotnet build command with sudo dotnet build , so it turned out to be a permissions issue and the app started fine with dotnet bin/Debug/netcoreapp2.0/MyApp.dll .我在 Ubuntu Linux 上遇到了这个错误,并且第一次尝试从 CLI 运行它,所以我通过使用sudo dotnet build运行 dotnet build 命令来修复它,所以它原来是一个权限问题并且应用程序启动正常使用dotnet bin/Debug/netcoreapp2.0/MyApp.dll Sadly the build command didn't notify about the permissions issue.遗憾的是,构建命令没有通知权限问题。

If anyone encountered this problem in VS 2022 when a new MVC ASP.NET project is created, I had to execute如果有人在创建新的 MVC ASP.NET 项目时在 VS 2022 中遇到此问题,我必须执行

dotrun watch run and than Debug the visual studio project. dotrun watch run ,然后Debug Visual Studio 项目。 The problem went away.问题消失了。

I am not sure why doesn't dotrun start by default when in debug mode.我不确定为什么在调试模式下默认不启动 dotrun 。

To enable runtime compilation for all environments in an existing project:为现有项目中的所有环境启用运行时编译:

  1. Install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package.安装 Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet 包。 Install-Package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation安装包 Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

  2. Update the project's Startup.ConfigureServices method to include a call to AddRazorRuntimeCompilation.更新项目的 Startup.ConfigureServices 方法以包含对 AddRazorRuntimeCompilation 的调用。 builder.Services.AddRazorPages().AddRazorRuntimeCompilation(); builder.Services.AddRazorPages().AddRazorRuntimeCompilation();

i was also facing similar issue,took long time to fix... Solution is in .csproj if any views are with Remove then delete those entry and include those views to project in solution explorer... then actual fix is just add one test view viewfile index3.cstml and make it called from action then deploy all works well.我也遇到了类似的问题,花了很长时间来修复...如果有任何视图带有 Remove 则解决方案在 .csproj 中,然后删除这些条目并将这些视图包含在解决方案资源管理器中的项目中...然后实际修复只是添加一个测试查看视图文件 index3.cstml 并使其从操作中调用,然后部署一切正常。 Later can remove that extra view file.稍后可以删除该额外的视图文件。 100% it works. 100% 有效。 enter link description here 在此处输入链接描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解决区域中 ASP.NET Core MVC 中的“未找到视图”错误? - How do I solve the 'View not found' error in ASP.NET Core MVC in areas? ASP.NET Core异常“未找到视图” - ASP.NET Core exception “View was not found” 如何在 ASP.NET Core MVC“待办事项”应用程序中提取 URL 的文件名并在视图中显示给用户? - How do I extract the filename of a URL in a ASP.NET Core MVC "To Do" app and show it to the user in the View? 如何在 asp.net 内核中捕获或抛出异常? - How do i catch or throw an exception in asp.net core? 如何在ASP.NET MVC 5项目中获得“添加控制器”和“添加视图”菜单选项? - How do I get the “Add Controller” and “Add View” menu options in my ASP.NET MVC 5 project? 如何在 ASP.NET Core 中排除项目依赖项? - How do I exclude project dependencies in ASP.NET Core? 我无法在 ASP.NET MVC 5. 应用程序的视图中转换我的日期时间格式。 我该如何解决? - I can't convert my datetime format in the View of a ASP.NET MVC 5. Application. How do I solve it? 如何解决 ASP.NET Core MVC 应用程序中的迁移问题? - How to solve migration problem in ASP.NET Core MVC app? 如何在 ASP.NET MVC 视图中对数据进行分组? - How do I group data in an ASP.NET MVC View? 如何在ASP.NET Webforms网站项目中一起使用Webforms和ASP.NET MVC? - How do I use Webforms and ASP.NET MVC together in an ASP.NET Webforms Website project?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM