0

場景:我最近添加了一個組件到我的ASP.NET MVC應用程序,允許他們將文件上傳到數據庫中。由於這些文件平均超過2MB,我選擇使用FILESTREAM。我將HttpPostedFileBase保存爲臨時文件,執行一些業務邏輯,然後上載文件。上傳後,用戶將被重定向到一個頁面,該頁面在瀏覽器中內聯查看文件。下面是相關的上傳代碼:SQL FILESTREAM打破

var DocContext = new DocumentEntities(); 
var dbFile = new File 
{ 
    DocumentID = Guid.NewGuid(), 
    Name = fileName, 
    Type = file.ContentType 
}; 
DocContext.Document.Add(dbFile); 
DocContext.SaveChanges(); 

using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted })) 
using (var sqlFS = dbFile.Open(DocContext, FileAccess.Write)) 
using (var tempFS = tempFile.OpenRead()) 
{ 
    tempFS.CopyTo(sqlFS); 
    scope.Complete(); 
} 

下面是相關查看/下載代碼:

public ActionResult File(Guid? id = null) 
{ 
    if (id == null) 
     return RedirectToActionPermanent("Index"); 

    return File(DocContext.Document.Find(id.Value) as File); 
} 

private ActionResult File(File file) 
{ 
    if (file == null) 
     throw new HttpException(404, "Unknown document type"); 

    var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead }); 
    Disposing += d => { scope.Complete(); scope.Dispose(); }; 

    var fs = file.Open(DocContext, FileAccess.Read); 
    Disposing += d => fs.Dispose(); 

    return new Misc.InlineFileStreamResult(fs, file.MimeType) { FileDownloadName = file.FileName, Inline = true }; 
} 

和開放的方法:

public partial class File 
{ 
    public SqlFileStream Open(DocumentEntities db, FileAccess access) 
    { 
     var path = db.Database.SqlQuery<string>(
      @"SELECT FileData.PathName() FROM [File] WHERE DocumentID = @docID", 
      new SqlParameter("docID", DocumentID)).First(); 
     var context = db.Database.SqlQuery<byte[]>(
      @"SELECT Get_FILESTREAM_TRANSACTION_CONTEXT() FROM [File] WHERE DocumentID = @docID", 
      new SqlParameter("docID", DocumentID)).First(); 

     return new SqlFileStream(path, context, access); 
    } 
} 

查看以前上傳的文件精美作品。查看用戶上傳的文件(最近?),發生以下異常: The transaction operation cannot be performed because there are pending requests working on this transaction.

發生了什麼事?

更新:我假設因爲我是一個SQL系統管理員,我可以上傳文件並查看他們罰款。

回答

0

當數據庫條目具有MIME類型而不是類型列中的擴展名時,我使用IIS和web.config來推斷給出該文件的擴展名。但普通用戶沒有權限讀取web.config。因此,當非服務器管理員用戶試圖查看使用MIME類型而不是擴展名存儲的文件時,我的例程會拋出權限異常,這會以某種方式觸發事務操作異常。不知道如何。