RazorLight RazorLight.TemplateNotFoundException: Project can not find template with key
Asked Answered
L

0

7

I am trying to generate HTML based on a .cshtml file, which is embedded:

<EmbeddedResource Include="Templates\ReportTemplate.cshtml" />

However, from RazorLight I always get the following Exception:

 RazorLight.TemplateNotFoundException: Project can not find template with key My.Namespace.Application.Templates.ReportTemplate.cshtml
   at RazorLight.Compilation.RazorTemplateCompiler.CreateRuntimeCompilationWorkItem(String templateKey)
   at RazorLight.Compilation.RazorTemplateCompiler.OnCacheMissAsync(String templateKey)
   at RazorLight.Compilation.RazorTemplateCompiler.CompileAsync(String templateKey)
   at RazorLight.EngineHandler.CompileTemplateAsync(String key)
   at RazorLight.EngineHandler.CompileRenderAsync[T](String key, T model, ExpandoObject viewBag)

But when I check the embedded resources, I can clearly see the embedded resource :

string[] files = Assembly.GetExecutingAssembly().GetManifestResourceNames();

files contains: My.Namespace.Application.Templates.ReportTemplate.cshtml

Here is my code to generate the PDF:

private async Task<string> RenderRazorTemplate(string key, Type viewModelType, object viewModel)
    {

        string[] files = Assembly.GetExecutingAssembly().GetManifestResourceNames();
        var engine = new RazorLightEngineBuilder()
            .UseEmbeddedResourcesProject(Assembly
            .GetExecutingAssembly()) // Use the Executing Assembly as project that embeds the .cshtml templates
            .SetOperatingAssembly(viewModelType.Assembly) // Without this, you'll get a Exception saying that the Assembly can't find the AntiForgery.dll
            .UseMemoryCachingProvider()
            .Build();
        
        return await engine.CompileRenderAsync(key, viewModel);
    }

My parameters are: Key: My.Namespace.Application.Templates.ReportTemplate.cshtml

I am using RazorLight.NetCore3 Version 3.0.2

Langobardic answered 4/8, 2021 at 6:19 Comment(1)
For the error of "Project can not find template with key", you can refer to this article, which may be helpful to you:github.com/toddams/RazorLight/issues/378.More use of RazorLight:github.com/toddams/RazorLightOaten

© 2022 - 2024 — McMap. All rights reserved.