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

Viewed 3331

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();
4 Answers

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.

One of the causes of this problem can be the build action of the cshtml file.

  • Go to the cshtml file that have this issue.
  • Right click it and change properties [ or click Alt + Enter ]
  • Change the property named Build Action from None to Content

As shown in the images below:

None is selected

Open DDL

Select Content

since you are using controllers you have to add

builder.Services.AddControllersWithViews();

May be your applicaiton is opening on VS2019, please open the project in VS2022, issue will be fixed.

Related