如何解决ASP.NET Core MVC项目中的“视图未找到”异常

65
我正在尝试使用VS Code在OSX上创建一个运行ASP.NET Core MVC测试应用程序。 当访问默认的Home/index(或我尝试的任何其他视图)时,我遇到了“视图未找到”的异常。
这是启动配置。
    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}"
            );
        });
    }

我在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"
},

最后,这是我收到的异常。

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 --- ...

有什么建议是我可能忽略了的吗?


请展示一下你的HomeController代码。 - Lukasz Mk
1
检查文件名 -> index.cshtml -> Index.cshtml - Lukasz Mk
1
将视图从项目中排除,然后再次包含即可解决问题!!! - Nima Talebi
@NimaTalebi 的解决方案对我很有帮助! - Kevin Dark
33个回答

-1
我遇到了同样的错误,但是问题和解决方法不同。我在构建输出中找到了这个警告。
20>CSC : warning CS8785: Generator 'RazorSourceGenerator' failed to generate source. 
It will not contribute to the output and compilation errors may occur as a result. 
Exception was of type 'ArgumentException' with message 
'The hintName 'Templates_ChangeLog_cshtml.g.cs' of the added source 
file must be unique within a generator.

链接了一个同名文件,导致RazorSourceGenerate停止。 解决后,一切正常运作。


-1
我运行了Visual Studio 2022的更新,升级到了17.7.6版本,问题得到了解决。

-1
尝试从csproject中删除这段代码。
<Target Name="DisableAnalyzers" BeforeTargets="CoreCompile">
    <ItemGroup>
        <Analyzer Remove="@(Analyzer)" />
    </ItemGroup>
</Target>

感谢您对Stack Overflow社区做出贡献的兴趣。这个问题已经有很多答案了,其中一个答案已经得到社区广泛验证。您确定您的方法之前没有被提到过吗?如果是这样的话,能否解释一下您的方法与众不同的地方,在什么情况下您的方法可能更好,并且/或者为什么您认为之前的答案不够满意。您可以编辑您的回答并提供解释吗? - Jeremy Caney

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接