>source

Visual Studio 2019에서 ASP.NET Core 5 애플리케이션 프로젝트를 만들었습니다.

요구 사항은 뷰를 미리 컴파일하지 않아야한다는 것입니다.

그래서 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

Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful (IEnumerable 1 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](IHttpApplication 신청 1 건) 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;
    }
}

도와주세요. 미리 감사드립니다

  • 답변 # 1

    이 설정은 .net core 2.x에서 사용할 수 있지만 .net core 5에서는 런타임 컴파일을 활성화 할 수 없습니다.

    이 경우 다음을 사용할 수 있습니다. AddRazorRuntimeCompilation 런타임 컴파일을 활성화합니다.

    public void ConfigureServices(IServiceCollection services)
     {
         services.AddControllersWithViews()
             .AddRazorRuntimeCompilation();
     }
    
    

    또 다른 방법은 조건부로 런타임 컴파일을 활성화하는 것입니다.

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

    이 문서를 참조 할 수 있습니다.

    나는 편집한다 Index.cshtml 편집기에서.

    그런 다음 게시 폴더에 저장하고 프로젝트를 시작합니다. 이렇게 컴파일했습니다.

관련 자료

  • 이전 c++ - 정책 기반 설계 - 기본 클래스 (함수)의 조건부 사용
  • 다음 powershell - Windows Power Shell에서 속성 파일 값을 어떻게 추출하여 env var에 저장합니까?