John Hpa
John Hpa

Reputation: 463

ASP.NET Core 5 application cannot find view error

I've created an ASP.NET Core 5 application project in Visual Studio 2019.

The requirement is that the views should not be precompiled.

So I set the RazorCompileOnPublish to false:

<RazorCompileOnPublish>false</RazorCompileOnPublish>

in the .csproj file.

After publishing the project, the Views folder was copied to the published directory.

But at runtime, I got the following error.

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(IEnumerable1 originalLocations) at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result) at Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultAsync>g__Logged|21_0(ResourceInvoker invoker, IActionResult result) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task) at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.HandleException(HttpContext context, ExceptionDispatchInfo edi) at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication1 application) dbug: Microsoft.AspNetCore.Server.Kestrel[9] *

The program.cs and Startup.cs files are as follows:

public class Startup
{        
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration) {
        Configuration = configuration;
    }     

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services) {
        services.AddControllersWithViews();           
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        }
        else {
            app.UseExceptionHandler("/Home/Error");
        }          
        app.UseStaticFiles();

        app.UseRouting();
        app.UseAuthorization();

        app.UseEndpoints(endpoints => {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            //endpoints.MapRazorPages(); //Has no effect
        });
    }
}

public class Program {
    public static void Main(string[] args) {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) {
        Console.WriteLine($"ContentRoot set to: {Directory.GetCurrentDirectory()}");
        var hostBuilder = Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder => {
                webBuilder.UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())                    
                .UseStartup<Startup>();
            });
        return hostBuilder;
    }
}

Please help. Thanks in advance

Upvotes: 3

Views: 3905

Answers (1)

Karney.
Karney.

Reputation: 5031

This setting can be used in .net core 2.x, but cannot enable runtime compilation in .net core 5.

  1. In this case, you can use AddRazorRuntimeCompilation to enable runtime compilation.

    public void ConfigureServices(IServiceCollection services)
     {
         services.AddControllersWithViews()
             .AddRazorRuntimeCompilation();
     }
    
  2. The another way is to enable runtime compilation conditionally.

    public Startup(IConfiguration configuration,IWebHostEnvironment webHostEnvironment)
     {
         Configuration = configuration;
         Env = webHostEnvironment;
     }
     //...
     public IWebHostEnvironment Env { get; set; }
    
     public void ConfigureServices(IServiceCollection services)
     {
         IMvcBuilder builder = services.AddRazorPages();
    
         if (!Env.IsDevelopment())
         {
             builder.AddRazorRuntimeCompilation();
         }
         services.AddControllersWithViews();
     }
    

And you can refer to this document.

I edit Index.cshtml in editor.

enter image description here

Then save it in publish folder and start the project. It compiled as this.

enter image description here

Upvotes: 5

Related Questions