asp.net-core - ASP.NET Core 5 应用程序找不到 View 错误

标签 asp.net-core .net-5

我在 Visual Studio 2019 中创建了一个 ASP.NET Core 5 应用程序项目。

要求是 View 不应该被预编译。

所以我将 RazorCompileOnPublish 设置为 false:

<RazorCompileOnPublish>false</RazorCompileOnPublish>

.csproj文件。

发布项目后,Views文件夹已复制到发布目录。

但是在运行时,我得到了以下错误。

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] *

program.cs和Startup.cs文件如下:

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;
    }
}

请帮忙。提前致谢

最佳答案

此设置可以在.net core 2.x中使用,但不能在.net core 5中启用运行时编译。

  1. 在这种情况下,您可以使用 AddRazorRuntimeCompilation 启用运行时编译。

    public void ConfigureServices(IServiceCollection services)
     {
         services.AddControllersWithViews()
             .AddRazorRuntimeCompilation();
     }
    
  2. 另一种方法是有条件地启用运行时编译。

    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();
     }
    

你可以引用这个document .

我在编辑器中编辑 Index.cshtml

enter image description here

然后将其保存在发布文件夹中并启动项目。编译成这样。

enter image description here

关于asp.net-core - ASP.NET Core 5 应用程序找不到 View 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65245851/

相关文章:

c# - 如何使用 LINQ 在 ASP.NET Core 中从 ModelState 中获取充满错误消息的 IEnumerable

.net - 无法在 visual studio 2019 中运行 IIS Express

garbage-collection - 强制 WeakReference 的目标被垃圾回收

c# - 如何解决 Visual Studio 2019 com 中的错误 MSB3644。版?

.net-core - 即使我使用 .Net Core 3.1,我也可以更新到 .Net 5 NuGet 包吗?

c# - 处理服务结构中的异常

asp.net-core - 使用库中的可配置路径映射 Controller 路由

c# - 使用 Autofixture 生成副本

c# - .net5 上的函数 : No job functions found. 尝试将您的作业类和方法公开

c# - 如何将参数传递给通用操作过滤器