繁体   English   中英

托管 asp.net 应用程序 DirectoryNotFoundException

[英]Hosted asp.net application DirectoryNotFoundException

我有一个应用程序在我的本地服务器上运行。 该应用程序在本地运行,没有任何错误。 但是,当我在Heroku中托管应用程序时。 它产生的错误为:

DirectoryNotFoundException: Could not find a part of the path'/app/heroku_output/EmailTemplate/EmailConfirm.html'.

我一直在尝试使用以下代码读取文件:

private const string templatePath = @"EmailTemplate/{0}.html";

private string GetEmailBody(string templateName)
{
    var body = File.ReadAllText(string.Format(templatePath, templateName));
    return body;
}

如图所示,文件夹EmailTemplate在我的根目录中。

在此处输入图像描述

该文件夹也已上传到 Github 并正确托管在 Heroku 中。 但是应用程序正在查看错误项目目录中的文件,即 (/app/heroku_output)。

我的代码中缺少什么? 我该如何阅读这些目录?

查找所有已部署的文件后,

您尝试读取文件。 可以在wwwroot文件夹中读取文件。 所以把你的模板移到那里。 要访问wwwroot文件夹,请使用作为 IWebHostEnvironment 注入的IWebHostEnvironment中的WebRootPath属性

public class EmailTemplateGenerator
{
    private IWebHostEnvironment _env;
    public EmailTemplateGenerator(IWebHostEnvironment env)
    {
        _env = env;
    }

    public void GetEmailBody(string templateName)
    {
        var template = File.OpenRead(Path.Combine(_env.WebRootPath, $"EmailTemplate/{templateName}.html")
    }
}

尝试以下操作:

在 Visual Studio 中

如果您使用 Visual Studio 发布,请右键单击“EmailTemplate”文件夹和 select“属性”下的每个文件,并将“复制到 Output 目录”的值设置为“始终复制”。 这将使 Visual Studio 将这些文件发布到托管环境。 如果您使用不同的应用程序发布文件,只需确保将“EmailTemplate”文件夹发布到托管环境。

在代码中

为了安全起见,请始终通过基础 URL 访问您的文件。 下面给出示例。

//private const string templatePath = @"EmailTemplate/{0}.html";
private const string templatePath = @"EmailTemplate\\{0}.html";

private string GetEmailBody(string templateName)
{
    //var body = File.ReadAllText(string.Format(templatePath, templateName));
    string baseURL = AppDomain.CurrentDomain.BaseDirectory;
    var body = File.ReadAllText(string.Format(baseURL + "\\" + templatePath, templateName));
    return body;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM