【问题标题】:ASP .NET Core 3.1 IFormFile read a file from hostingASP .NET Core 3.1 IFormFile 从主机读取文件
【发布时间】:2021-12-28 09:38:59
【问题描述】:

我想从主机向注册用户发送一个文件,并附上确认电子邮件。

我的电子邮件发件人类接受包含 public IFormFileCollection Attachments { get; set; } 的消息模型

我的问题:我无法从主机读取文件并将其转换为 IFormFile。

这是我的一段代码:

var pathToEmailAttachment = _webHostEnvironment.WebRootPath
+ Path.DirectorySeparatorChar.ToString()
+ "pdf"
+ Path.DirectorySeparatorChar.ToString()
+ "MyFile.pdf";

IFormFile file;

using (var stream = System.IO.File.OpenRead(pathToEmailAttachment))
{
    file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name));
}

var message = new Message(new string[] { user.Email }, messageSubject, emailMessage, new FormFileCollection() { file });

await _emailSender.SendEmailAsync(message);

消息模型:

public class Message
{
    public List<MailboxAddress> To { get; set; }
    public string Subject { get; set; }
    public string Content { get; set; }
    public IFormFileCollection Attachments { get; set; }

    public Message()
    {

    }

    public Message(IEnumerable<string> to, string subject, string content, IFormFileCollection attachments)
    {
        To = new List<MailboxAddress>();

        To.AddRange(to.Select(x => new MailboxAddress(x, x)));
        Subject = subject;
        Content = content;
        Attachments = attachments;
    }
}

任何建议或帮助将不胜感激。

【问题讨论】:

  • 我建议将Message转换为内部实体,然后添加额外的附件将是微不足道的。
  • 我认为问题在于读取文件并将其填充到 IFormFile 中。也许我需要更改 using 语句。
  • 确定文件存在于 wwwroot/pdf 文件夹中吗?
  • 是的,它在 wwwroot/pdf 中。

标签: c# asp.net-core iformfile


【解决方案1】:

可能有两个问题,不正确的FormFile 实例化和文件流的提前关闭。所以你可以尝试在this answer 的帮助下修复FormFile 创建并扩展using 语句

using (var stream = System.IO.File.OpenRead(pathToEmailAttachment))
{
    file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
    {
        Headers = new HeaderDictionary(),
        ContentType = "you content type"
    };

    var message = new Message(new string[] { user.Email }, messageSubject, emailMessage, new FormFileCollection() { file });

    await _emailSender.SendEmailAsync(message);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    相关资源
    最近更新 更多