【问题标题】:.NetCore: How to include folder in production?.Net Core:如何在生产中包含文件夹?
【发布时间】:2021-08-10 10:55:43
【问题描述】:

所以我有这个代码来发送电子邮件。代码尝试为电子邮件模板查找.cshtml

这是我的文件夹层次结构:

Project
-- Email
---- EmailConfirmation.cshtml
---- ResetPassword.cshtml

这是找到模板的代码:

public static string GetEmailTemplate(string templateName)
{
    string path = Path.Combine(Config.Env.ContentRootPath, "Email", templateName);
    string content = "";

    // This text is added only once to the file.
    if (File.Exists(path))
    {
        // Create a file to write to.
        content = File.ReadAllText(path);
    } 
    else
    {
        throw new Exception("The email template could not be found");
    }

    return content;
}

Debug 中,运行完美,但在生产中,代码找不到模板。

如何将模板包含在发布包中?

我在我的.csproj 中试过这个:

<ItemGroup>
    <Folder Include="ClientApp\" />
    <Folder Include="Migrations\" />
    <Views Include="Email\**" />
</ItemGroup>

它不工作。


编辑

我试图设置这个:

但还是不行。

【问题讨论】:

  • 试试这个 var path = Path.GetFullPath(Path.Combine(Config.Env.ContentRootPath, "Email", templateName));
  • 你的方法行不通。搜索render razor view to string,或使用github.com/Tyrrrz/MiniRazor之类的库
  • 如果剃刀模板中的逻辑为零,则可以将它们标记为EmbeddedResource,并在运行时从程序集中读取它们,但如果需要通过渲染阶段,请参阅我之前的评论

标签: asp.net-core asp.net-core-mvc asp.net-core-webapi


【解决方案1】:

你能试试这个吗?

string workingDirectory = Environment.CurrentDirectory;

string projectDirectory=Directory.GetParent(workingDirectory).Parent.Parent.FullName;

它将为您提供项目目录的路径。然后你完成指向你的文件的子目录。

【讨论】:

    【解决方案2】:

    所以我的问题是 Email 文件夹未复制到已发布的包中。将此代码添加到.csproj

      <ItemGroup>
        <None Include="Email\EmailConfirmation.cshtml">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
        <None Include="Email\ResetPassword.cshtml">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
      </ItemGroup>
    

    或者你可以在项目资源管理器中这样设置:

    由于某种原因,必须将构建操作设置为None,因为.NetCore 会以不同的方式对待Content,并且不会将文件夹复制到发布包中(可能内容会合并到@987654329 @,我不知道)。

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 2022-01-18
      • 2018-04-13
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 2018-01-28
      相关资源
      最近更新 更多