-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathRazorViewToStringRenderer.cs
40 lines (35 loc) · 1.23 KB
/
RazorViewToStringRenderer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using Contracts.Dtos.Requests;
using RazorLight;
namespace Infrastructure.Services.Mail;
public class RazorViewToStringRenderer
{
public static async Task<string> RenderViewToStringAsync(MailTemplate mailTemplate)
{
RazorLightEngine razorEngine = CreateRazorlight(mailTemplate.Template.GetType());
try
{
var template = await File.ReadAllTextAsync(GetPath(mailTemplate.ViewName));
return await razorEngine.CompileRenderStringAsync(
mailTemplate.ViewName,
template,
mailTemplate.Template
);
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Failed to render view {mailTemplate.ViewName}. Exception: {ex.Message}"
);
}
}
private static string GetPath(string viewName)
{
string root = Path.Join(Directory.GetCurrentDirectory(), "wwwroot");
return Path.Combine(root, "Templates", $"{viewName}.cshtml");
}
private static RazorLightEngine CreateRazorlight(Type type) =>
new RazorLightEngineBuilder()
.UseEmbeddedResourcesProject(type)
.UseMemoryCachingProvider()
.Build();
}