尝试发送带有附件的电子邮件。但是我收到一个错误:
“无法从 'System.Threading.Tasks.Task'到 'System.Net.Mail.Attachment'
我的错误发生在Attachments.Add(GetAttachment(attachmentFileName));
行
我尝试了各种转换(请参阅代码),但我不太清楚问题出在哪里。我知道解决方案就在我眼前,但我看不到。
public class NonFERosterEmail : BaseNotificationEmail<OfferViewModel>
{
public NonFERosterEmail(OfferViewModel vm, string emailList, string attachmentFileName) : base(vm)
{
To.AddRange(GetTo(emailList));
Body = GetBody();
Subject = GetSubject();
//Attachments.Add(new Attachment(GetAttachment(attachmentFileName)));
Attachments.Add(GetAttachment(attachmentFileName));
From = new MailAddress(ConfigurationManager.AppSettings["RedirectEmailTo"]);
}
//public async Task<List<Attachment>> GetAttachment(string attachmentFileName)
public async Task<Attachment> GetAttachment(string attachmentFileName)
{
//var ret = new List<Attachment>();
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["azureStorageAccount"]);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("attachments");
CloudBlockBlob blob = container.GetBlockBlobReference(attachmentFileName);
var contentType = MimeMapping.GetMimeMapping(attachmentFileName);
Stream target = new MemoryStream();
await blob.DownloadToStreamAsync(target);
target.Position = 0;
//ret.Add(new Attachment(target, attachmentFileName, contentType));
Attachment ret = new Attachment(target, attachmentFileName, contentType);
return ret;
}
//remainder of code left out for brevity
}
我希望GetAttachment
返回正确的附件对象,该对象将被添加到邮件对象并成功发送。
答案 0 :(得分:1)
要从Task<T>
获取值,必须使方法async
和await
成为任务。
答案 1 :(得分:1)
在返回await
的调用方法时,您需要Task
,所以要代替
Attachments.Add(GetAttachment(attachmentFileName));
使用:
Attachments.Add(await GetAttachment(attachmentFileName));
或
Attachments.Add(GetAttachment(attachmentFileName).GetAwaiter().GetResult());
答案 2 :(得分:1)
我认为@SLaks和@Roman Marusyk的答案是正确的,但是看起来您正在从构造器中调用GetAttachment
,这不是异步的。因此,如果不使用await
方法,将无法使用async
。尝试使用GetAttachment
的result属性,如下所示。
Attachments.Add(GetAttachment(attachmentFileName).Result);
一个更好的解决方案是使用.GetAwaiter().GetResult()
,正如@Roman Marusyk指出并在this post中显示的那样,如果该方法失败,它将直接抛出异常,而不是抛出{{1} }。
更好的解决方案是使用以下内容
AggregateException