Tim
Tim

Reputation: 1249

RazorEngine Could not resolve template

I have a console application that uses RazorEngine to send email based on the run of the application. I am successfully able to send emails both in the development IDE and from running the console application via the executable. However when I run the console application from a scheduled task I receive an error "Could not resolve template" on line,

var emailHtmlBody = Engine.Razor.RunCompile("ResponseErrors.cshtml", null, model);

has anyone run into this?

var config = new TemplateServiceConfiguration
 {
    TemplateManager = new ResolvePathTemplateManager(new[] {"EmailTemplates"}),
    DisableTempFileLocking = true
 };

 Engine.Razor = RazorEngineService.Create(config);
 var emailHtmlBody = Engine.Razor.RunCompile("ResponseErrors.cshtml", null, model);

UPDATE 1:

UPDATE 2:

There is no RazorEngine... folder that was created in the user's temp folder.

UPDATE 3:

I just created a sample console app and it's now doing the same thing in the IDE. I put it up on GitHub as RazorEngine_Test

UPDATE 4:

It seems that the TemplateServiceConfiguration is not working as designed or the examples I worked off of are incorrect. I updated the test project with the 2 lines below and that solved my issue. I don't think this was the intended implementation method but it works. Posting because I know someone will run into the same issue.

string path = AppDomain.CurrentDomain.BaseDirectory;
string filePath = $"{path}EmailTemplates\\ExceptionEmail.cshtml";

Upvotes: 3

Views: 3594

Answers (2)

Fabian Kamp
Fabian Kamp

Reputation: 174

Had the same Problem my solution was changing the Project file ProjectName.csproj external and adding the View as content and not as None from

    <None Include="Views/Folder/Name.cshtml"/>

to

    <Content Include="Views\Emails\Name.cshtml">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>

Upvotes: 2

Tim
Tim

Reputation: 1249

So I was able to confirm the fix in Production today. Adding those 2 lines did correct the problem. So the complete code block for this is

 var config = new TemplateServiceConfiguration
 {
    TemplateManager = new ResolvePathTemplateManager(new[] {"EmailTemplates"}),
    DisableTempFileLocking = true
 };

 string path = AppDomain.CurrentDomain.BaseDirectory;
 string filePath = $"{path}EmailTemplates\\ExceptionEmail.cshtml";

 Engine.Razor = RazorEngineService.Create(config);
 var emailHtmlBody = Engine.Razor.RunCompile(filePath, null, model);

Upvotes: 3

Related Questions