在本地调试 Azure 函数提供了通往 AppDomain.CurrentDomain.BaseDirectory 的有趣路径

Debugging Azure function locally gives a funny path to AppDomain.CurrentDomain.BaseDirectory

是否有更好的方法从我的解决方案中的 html 个文件调用和获取我的电子邮件模板?

我正在从 Azure 函数项目和我的 ASP.Net MVC 项目调用 'AppDomain.CurrentDomain.BaseDirectory' 以获取我的电子邮件模板的路径。 (.html 个文件)

但是从 Azure 函数发出的调用甚至没有 return 解决方案中的路径!

简单来说,ASP.Net MVC 和 Azure 函数项目都在另一个名为 projectName.Services 的项目中调用 EmailService.cs 来构造电子邮件。

在这两个项目中,我都这样调用 EmailService.cs

_emailService.CancelEventSendHostEmail(value1, someObject, anotherObject, "someMessage");

在 'CancelEventSendHostEmail' 我正在做这样的事情

CancelEventSendHostEmail(/*incoming properties*/) {

  var outerTemplateHtml = GetEmailTemplate("email-outer-body-template.html");
  var specificTemplate= GetEmailTemplate("someTemplate.html");
  // do some work to fill in values in the email
  // send the email
}

现在 GetEmailTemplate 看起来像这样

public StringBuilder GetEmailTemplate(string templateName)
{
    string htmlAsString 
            = File.ReadAllText(Path.Combine(Directory.GetParent(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).ToString()).ToString(), 
            @"Yogabandy2017.Services\EmailingTemplates", templateName));
        return new StringBuilder(htmlAsString);
 }

现在这可以很好地与 ASP.Net MVC 项目一起查找、获取和读取 HTML 模板文件作为字符串。 EmailService.cs 从 ASP.Net MVC 项目中发现文件没问题,但是当我从我的 Azure 函数调用 'GetEmailTemaplate' 时

AppDomain.CurrentDomain.BaseDirectory

路径return不在项目或解决方案目录中的路径。

它return是一条看起来像这样的路径

C:\Users\chuckdawit\AppData\Local\AzureFunctionsTools\Releases.2.0\cli\

好像我在 asp.net mvc 应用程序中并且我在文本中阅读 'AppDomain.CurrentDomain.BaseDirectory' return 是这样的路径

C:\Users\chuckdawit\Source\Workspaces\YogaBandy2017\YogaBandy2017\YogaBandy2017\

然后我可以在该项目的文件夹中搜索 html 电子邮件模板文件!

有API获取一个函数的当前文件夹:

public static HttpResponseMessage Run(HttpRequestMessage req, ExecutionContext context)
{
    var message = $"You are in {context.FunctionDirectory}";
    return req.CreateResponse(System.Net.HttpStatusCode.OK, message );
}

参见documentation

FunctionDirectory: Provides the current function directory (e.g. when running on Azure, d:\home\site\wwwroot\HttpTrigger1)

请注意,在本地它将位于 bin\debug 内。仔细计划如何部署与 Function 文件夹相关的电子邮件模板。

一个明智的替代方法是将模板部署到 Blob 存储,然后使用输入绑定将它们加载到 Function 中,无需代码。

要获取函数的当前文件夹,我们可以这样做:

string currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

结果截图: