3

_Layout.cshtml在使用in的嵌入式资源时,我正在努力使电子邮件正常工作FluentEmail

这是我得到的异常错误:

Project can not find template with key _Layout.cshtml

这是我到目前为止的设置:

在 ConfigureServices 中Program.cs,我添加了RazorRenderer如下内容:

//Set email service using FluentEmail
 services.AddFluentEmail("appname@domain.com")
 .AddRazorRenderer(typeof(Program))
 .AddSmtpSender("smtp.somesmtp.com", 25)
 .AddSmtpSender(new System.Net.Mail.SmtpClient() { });

在我的内部NotificationService.cs,我总是陷入那个异常块:

private async Task SendEmailAsync<TModel>(string subject, TModel model)
{
    try
    {
        using (var scope = _serviceProvider.CreateScope())
        {
            var email = await scope.ServiceProvider.GetRequiredService<IFluentEmail>()
                    .To(string.Join(";", _emailRecipients))
                    .Subject(subject)
                    .UsingTemplateFromEmbedded("AppName.Views.Emails.SomeReport.cshtml", model, GetType().Assembly)
                    .SendAsync();
        }
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Failed to send email. Check exception for more information.");
    }
}

SomeReport.cshtml里面Views\Emails\SomeReport.cshtml是这样的:

@using System;
@using RazorLight;
@using System.Collections.Generic;
@using AppName.Models;

@inherits TemplatePage<IEnumerable<SomeReport>>
@{
    @* For working with Embedded Resource Views *@
    Layout = "_Layout.cshtml";
}

@* Work with the Model here... *@

_Layout.cshtml里面Views\Shared\_Layout.cshtml是这样的:

@using RazorLight;
@* Some common layout styles here *@
@RenderBody()

SomeReport.cshtml和都是_Layout.cshtml嵌入式资源:

我的参考资料有RazorLight完整的FluentEmail.Razor包。

如果有帮助,这是一个.NET 5 Worker Service项目,我还在文件中添加了PreserveCompilationContext和:PreserveCompilationReferences.csproj

<PropertyGroup>
  <TargetFramework>net5.0</TargetFramework>
  <PreserveCompilationContext>true</PreserveCompilationContext>
  <PreserveCompilationReferences>true</PreserveCompilationReferences>
</PropertyGroup>

我到处都看过,但仍然没有找到解决方案。如此简单的事情一直难以奏效。请帮忙。

谢谢!

4

2 回答 2

0

在您的模板中,而不是:

Layout = "_Layout.cshtml"

尝试:

Layout = ""./Shared/_Layout.cshtml""
于 2021-07-30T09:53:43.290 回答
0

告诉 Razorlight 您正在使用这样的嵌入式资源:

Email.DefaultRenderer = new RazorRenderer(typeof(Assembly.SomeClassInsideAssembly));

或在启动中:

.AddRazorRenderer(typeof(Assembly.SomeClassInsideAssembly));

然后在您的视图中指定相对于“SomeClassInsideAssembly”的布局页面:

@{
    Layout = "Views._Layout.cshtml";
}
于 2021-10-18T20:47:40.963 回答