Jesper Kristiansen
Jesper Kristiansen

Reputation: 1959

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

"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 ?

Upvotes: 76

Views: 150637

Answers (30)

Ayhan Yenilmez
Ayhan Yenilmez

Reputation: 159

In TargetFramework .net6 or higher (in lower versions use startup.cs)

1- Install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package.

2- Add this code In Program.cs

If you use Razor Pages

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

If you use MVC Views

builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation(); 

The steps up to this point run the views correctly for the local runtime. However, you will continue to receive the view not found error on the server. To solve this, you should also follow the step below.

3- Add this in .csproj

<PropertyGroup>
...
...
<CopyRazorGenerateFilesToPublishDirectory>true</CopyRazorGenerateFilesToPublishDirectory>
</PropertyGroup>

Upvotes: 5

Daniel King
Daniel King

Reputation: 142

I ran the update for Visual Studio 2022, to Version 17.7.6, and it fixed the problem.

Upvotes: 0

Jose Chiconela
Jose Chiconela

Reputation: 1

try to remove this code from te csproject

<Target Name="DisableAnalyzers" BeforeTargets="CoreCompile">
    <ItemGroup>
        <Analyzer Remove="@(Analyzer)" />
    </ItemGroup>
</Target>

Upvotes: -1

flashsplat
flashsplat

Reputation: 537

For me, I simply rebuilt the solution and it resolved (VS 2022, ASP.net Core 6 MVC):

enter image description here

Upvotes: -1

sareno
sareno

Reputation: 696

I had the same issue. In my case, I had to change <CopyToOutputDirectory>Never</CopyToOutputDirectory> to <CopyToOutputDirectory>Always</CopyToOutputDirectory> from the .csproj file

Upvotes: 0

Molbac
Molbac

Reputation: 81

i got the same error but had a different problem/solution. i found this warning in the build output.

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.

a file with the same name was linked which caused RazorSourceGenerate to stop. after resolving that, everything worked.

Upvotes: -1

If you are using different areas, don't forget to add the [Area("Area-Name")] attribute to the controller.That was the issue in my case.

Upvotes: 1

Pravin Kamane
Pravin Kamane

Reputation: 61

I was facing this issue when I upgraded my .net application to .net core 6.0

<TargetFramework>net6.0</TargetFramework>
<AddRazorSupportForMvc>true</AddRazorSupportForMvc>

this AddRazorSupportForMvc setting helped to resolve this issue of "the-view-index-was-not-found"

Upvotes: 1

nammadhu
nammadhu

Reputation: 353

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. Later can remove that extra view file. 100% it works.enter link description here

Upvotes: 0

Ankursonikajen
Ankursonikajen

Reputation: 61

To enable runtime compilation for all environments in an existing project:

  1. Install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package. Install-Package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

  2. Update the project's Startup.ConfigureServices method to include a call to AddRazorRuntimeCompilation. builder.Services.AddRazorPages().AddRazorRuntimeCompilation();

Upvotes: 1

devyJava
devyJava

Reputation: 143

If anyone encountered this problem in VS 2022 when a new MVC ASP.NET project is created, I had to execute

dotrun watch run and than Debug the visual studio project. The problem went away.

I am not sure why doesn't dotrun start by default when in debug mode.

Upvotes: -1

Ajey
Ajey

Reputation: 35

I also got similar error. I am using .Net Core 6.0 ASP .Net MVC project.

It was resolved just by adding following in the 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>

Upvotes: 2

Mohammad S
Mohammad S

Reputation: 141

The solution of my project was by
1- Adding AddRazorRuntimeCompilation() such as services.AddControllersWithViews().AddRazorRuntimeCompilation(); into StartUp ConfigureServices.

2- and Keeping this <RazorCompileOnBuild>false</RazorCompileOnBuild>

in .csproj . Then Build the project.

Updated

Make sure you have this NuGet package added to your project:

Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

Upvotes: 14

Muhammad Waqar Anwar
Muhammad Waqar Anwar

Reputation: 440

I had the same problem in 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.

Upvotes: 12

Rob Lassche
Rob Lassche

Reputation: 851

Visual Code With dotnet version 2.2.300 gave an error message, so not a runtime exception.

My controller was derived from ControllerBase instead of Controller. So, I had to change ControllerBase to Controller.

Upvotes: 3

AK3800
AK3800

Reputation: 2298

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

dotnet myWebFolder/MyIdentityServer.dll

gave me the following output when Identity Server started:

Output log showing Content root path set to 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.

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. That change gave me this output:

Output log showing Content root path set to 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

Upvotes: 3

suadinho
suadinho

Reputation: 41

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.

It turns out windows-latest and latest visual studio in build pipeline wasn't actually mean windows 2022 and visual studio 2022 YET. And therefore published version wasn't supporting .net 6.

After specifying 2022 versions for both windows and visual studio it started working.

Here is the reference: https://github.com/dotnet/core/issues/6907

Upvotes: 4

klkn3103
klkn3103

Reputation: 11

I had the same problem under Arch Linux, Visual Studio Code and .NET Core 3.1 and 5.0.

I solved it by removeing the path to the csproj-file in the build section of the tasks.json file:

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

Upvotes: 1

Ryan Tavan
Ryan Tavan

Reputation: 131

In case of someone has a similar problem. It turned out that my csproj file has a few invalid references to my view. 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. things started working.

Upvotes: 1

Blaskowitz
Blaskowitz

Reputation: 93

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. Sadly the build command didn't notify about the permissions issue.

Upvotes: -1

Gerald Hughes
Gerald Hughes

Reputation: 6159

In my case the problem was from <EnableDefaultContentItems>false</EnableDefaultContentItems> that I had set in my csproj

Upvotes: 1

Elnoor
Elnoor

Reputation: 3752

In my case after migrating from Core 2.2 to 3.1 my static html file was not being found. In my startup.cs file I had to add app.UseDefaultFiles() just before app.UseStaticFiles() to make it work. 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?}");
   });
}

Upvotes: 0

Majid
Majid

Reputation: 3471

if you are porting your project from a console app to a web app, you need to change this line in your .csproj file

from:

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

to:

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

Upvotes: 7

FredyWenger
FredyWenger

Reputation: 2325

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

Upvotes: 2

NKR
NKR

Reputation: 2943

Check your .csproj file. 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.

Upvotes: 25

JohnnyFun
JohnnyFun

Reputation: 4293

I just upgraded from .net core 2.2 to 3. Two ways to resolve I found:

Either call AddRazorRuntimeCompilation() when configuring mvc, like:

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

more info here: https://learn.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:

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

Upvotes: 25

Ahmed El-Araby
Ahmed El-Araby

Reputation: 1232

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.

enter image description here

Upvotes: 86

Magne
Magne

Reputation: 17223

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. We got the error because wwwroot/bundle.js and wwwroot/style.js was mistakenly not initially committed, since our .gitignore included wwwroot. Discovered it by inspecting the network traffic and seeing it was these files giving the 404 and not the Index.cshtml itself.

Upvotes: 2

Agath
Agath

Reputation: 61

I am using 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). So I finally deleted the view, then I made it again, and this solved my problem.

Upvotes: 4

Kars Barendrecht
Kars Barendrecht

Reputation: 549

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.

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)

The solution was to rename the files to something else (e.g. xxx.cs ), commit and push, then rename them back to original with the correct casing/capitalization and commit and push again.

Upvotes: 4

Related Questions