【问题标题】:Project can not find template with key _Layout.cshtml项目找不到带有键 _Layout.cshtml 的模板
【发布时间】:2021-10-05 08:20:05
【问题描述】:

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

这是我得到的异常错误:

Project can not find template with key _Layout.cshtml

这是我目前的设置:

Program.cs 的 ConfigureServices 中,我将 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 都是嵌入式资源:

我的参考资料有 RazorLightFluentEmail.Razor 包。

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

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

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

谢谢!

【问题讨论】:

    标签: c# razor .net-5 razorlight


    【解决方案1】:

    在您的模板中,而不是:

    Layout = "_Layout.cshtml"
    

    尝试:

    Layout = ""./Shared/_Layout.cshtml""
    

    【讨论】:

    • 抱歉,没有解决任何问题。
    【解决方案2】:

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

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

    或在启动中:

    .AddRazorRenderer(typeof(Assembly.SomeClassInsideAssembly));
    

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

    @{
        Layout = "Views._Layout.cshtml";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      • 2018-06-28
      相关资源
      最近更新 更多