1
嗨,大家好,我正在嘗試向電子郵件中添加附件,但是我收到了這個奇怪的異常,並不清楚我做錯了什麼。 我從一個文件輸入的形式獲取附件System.Mail.Net無法訪問關閉的文件嘗試添加附件時出現異常
<div class="form-group">
<br/>
Select any files to attach to email
<div class="input-group">
<label class="input-group-btn btn btn-default btn-file" id="attachFiles">
Upload <input type="button" id="attach" name="Upload" style="display: none" value="Upload"/>
</label>
<label class="input-group-btn btn btn-default btn-file">
Browse <input type="file" id="attachInput" multiple="false" style="display: none"/>
</label>
<input type="text" disabled="disabled" id="attachText" class="form-control input-group-addon"/>
</div>
<br/>
<ul id="issueFormAttachName" class="list-group list-inline"></ul>
那麼我通過請求獲得此文件,並將其存儲在一個公共變量通過不同的控制器
[HttpPost]
[Route("home/saveAttachment")]
public ActionResult SaveAttachment()
{
try
{
EmailAttachments = new EmailAttachments
{
FileCollectionBase = Request.Files
};
return Json("Ok");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
日後訪問在此之後,我打電話給我的控制器發送使用此文件的電子郵件
string usersToReceived = "";
EmailMessage email = new EmailMessage
{
InnerHtmlBody = emailDto.EmailBody,
Subject = $"Support enquiry ticket number #{issueId}",
EmailHeader = "Thank you for contacting support"
};
emailDto.Users.ForEach(u => usersToReceived += u + ";");
Dictionary<string, Stream> streams = new Dictionary<string, Stream>();
//Check if attachments exist
if (HomeController.EmailAttachments?.FileCollectionBase.Count > 0)
{
foreach (string streamName in HomeController.EmailAttachments.FileCollectionBase)
{
streams.Add(streamName, HomeController.EmailAttachments.FileCollectionBase[streamName].InputStream);
}
foreach (string file in HomeController.EmailAttachments.FileCollectionBase)
{
//make sure stream is not disposed untill send is done
//Streams dont need to be explicitly disposed
email.AddAttachment(streams[file], file, HomeController.EmailAttachments.FileCollectionBase[file]?.ContentType);
}
}
email.Send(usersToReceived);
}
添加附件方法只是ca lls原生的附件構造函數(New Attachment(_ms, fileName, mediaType)
現在有時候我清除緩存並嘗試使用上面的代碼,這將工作,但大多數情況下,這將拋出一個異常與錯誤無法訪問關閉的文件任何人都知道這是怎麼回事?我也試過在末端明確的高速緩存方法,但並沒有工作
您的附件死於MVC管道。如果您將Request.Files內容重寫爲另一個ICollection變量,然後存儲它 - 它將像魅力一樣工作。 –
2017-04-18 10:36:29
謝謝你會去那裏 – Harry
嗨另一個問題,當我需要重寫它們在Request.Files或更晚的時候,或者在我打電話給發送之前?因爲我沒有看到我的應用程序離開MVC管道 – Harry