'Cannot find view 'Index', although index is there - ASP.NET Core 6 MVC

I am trying to run my asp.net application on localhost, but seem to get the following error:

An unhandled exception occurred while processing the request.

InvalidOperationException: The view 'Index' was not found. The following locations were searched:
/Views/Web/Index.cshtml
/Views/Shared/Index.cshtml
/Pages/Shared/Index.cshtml

I have my view located in Views > Web > Index.cshtml, although I still haven't found a way to resolve this issue. I have gone through the asp.net documentation and other stackoverflow posts. Can't seem to solve the issue.

Using:

  • Visual Studio 2019
  • ASP.NET Core 6
  • Windows 10

Here is the code in my program.cs file

    using UploadExcel.Context;
    using UploadExcel.Service;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddRazorPages();
    builder.Services.AddDbContext<DatabaseContext>();
    builder.Services.AddScoped<IWebService, WebService>();
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Web}/{action=Index}/{id?}");
    });
    
    app.MapRazorPages();
    
    app.Run();


Solution 1:[1]

If you are experiencing this issue on Visual Studio 2022, ASP.Net Core MVC (.NET 6), as an immediate solution what you can do is open a terminal where your *.csproj file resides and execute,

dotnet watch run

If you really want to use Visual Studio then you must update Visual Studio 2022 to version 17.1.0 + (your current version might be 17.0.4 or something). Refer this and this.

Solution 2:[2]

since you are using controllers you have to add

builder.Services.AddControllersWithViews();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nishan
Solution 2 Serge