首页 > 解决方案 > html 模板未加载:找不到路径“/Helpers/Email/Templates/template.html”的一部分

问题描述

我正在使用 .Net Core 2.1 Web Api。

我为此解决方案使用了 4 个项目。我正在尝试加载一个 html 模板,在本地工作正常,但是一旦我将它推送到 Linux 服务器中,由于此错误,文件无法加载:

html 模板未加载:找不到路径“/Helpers/Email/Templates/template.html”的一部分

解决方案的结构是下一个(包括文件夹和 html 文件):

- Core
- Helpers
   - Email
     EMailHelper.cs
     - Templates
       template.html
 - Infrastructure
 - WebApi (this is the main project, with appsettings.json, ...)

好吧,当我尝试从“EmailHelper.cs”加载“template.html”时,在 Windows 和 Mac 本地都可以正常工作,但是当我将它上传到发布环境(Azure - Linux)时,它总是抛出以前的例外。

“template.html”文件具有“复制在同一目录”并设置为“内容”作为构建操作。

还尝试使用以下网址加载文件:

const string htmlTemplate = "../Helpers/Email/Templates/template.html";

string emailTemplateUserRegistration = string.Format("..{0}Helpers{0}Email{0}Templates{0}{template.html}", Path.DirectorySeparatorChar);

但没有办法加载它。

你知道这是什么原因吗?我该如何解决?

提前致谢。

编辑:

奇怪,如果我加载这个 url 就无法从项目中加载文件:

/home/project/backend/Helpers/Email/Templates/template.html

但使用 vi 打开文件:

vi /home/project/backend/Helpers/Email/Templates/template.html

加载文件的方法如下:

 var builder = new StringBuilder();

 using (var reader = File.OpenText(htmlTemplate))
 {
      builder.Append(reader.ReadToEnd());
 }

标签: .netasp.net-coreasp.net-core-2.0

解决方案


这可能是因为您在 Azure 环境中运行时使用了错误的根路径。尝试使用依赖注入从 HostingEnviroment 获取路径。

public class MyController{

MyController(IHostingEnvironment env){

var path = env.ContentRootPath;
var myTemplatePath = path + "/Helpers/Email/Templates/template.html"

}

}

推荐阅读