2012-07-31 45 views
2

我的文件上傳在ASP MVC3網站上效果很好。目前這些文件保存在網站上名爲「文件」的文件夾中。用戶可以上傳任何類型的文件(例如myphoto.jpg,mydocument.docx等)。如何攔截對文件的請求以檢查MVC3中的權限?

當用戶上載我對存儲在SQL數據庫中的文件信息,並上傳誰是文件等

我的問題:

  1. 如何截取GET請求一個URL文件(例如/Files/myphoto.jpg)查看用戶是否被允許查看該文件? (根據他們在申請中的權利)?我不喜歡在允許訪問之前編寫路由約束來檢查數據庫的想法。
  2. 理想情況下,我想將這些文件存儲在與網站文件位置不同的位置,但是在某處網站可以確定該文件,並且它是來自請求的位置,但是可以像在位置一樣提供它的位置請求(正確的內容類型標題等)。
+0

這篇文章將幫助你http://prideparrot.com/blog/archive/2012/6/authorizing_folders_using_routeexistingfiles – VJAI 2012-07-31 09:40:10

回答

5

您可以將控制器添加到服務器的文件中。

public class FileController : Controller 
{ 

    private IFileStore _fileStore; 

    public FileController(IFileStrore fileStore) 
    { 
     this._fileStore = fileStore; 
    } 

    public ActionResult Index(string fileName) 
    { 
     // Do a database look up if the user has permission 
     if (_fileStore.HasPermission(fileName, User)) 
     { 
      // Flush the file content if the user has permission 
      var myfile = _fileStore.GetFile(fileName); 
      Response.ClearContent(); 
      Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.FileName); 
      Response.AddHeader("Content-Length", myfile.Length.ToString()); 

      Response.ContentType = myfile.Extension.ToLower(); 
      Response.WriteFile(myfile.FullName, false); 
      Response.Flush(); 
      Response.Close(); 
     } 
     else 
     { 
      // Return a Access Denied page 
      return View("NoPermission"); 
     } 
    } 

} 
+1

你打我:) – 2012-07-31 08:43:14

+1

可能值得一提的是,如果文件夾被允許,那麼這將需要一個'特殊'路線,就像這樣:'「文件/ {*文件名}」'爲了捕獲子文件夾。 – 2012-07-31 08:45:34

+0

謝謝!正是我需要的。 – mkaj 2012-07-31 20:08:04

0

你可以在你的web.config設置:

<!-- This section gives the authenticated user with myRole role access to all of the files that are stored in the images folder. --> 
<location path="images"> 
    <system.web> 
    <authorization> 
    <allow users =".\myRole" /> 
    </authorization> 
    </system.web> 
</location> 

http://msdn.microsoft.com/en-us/library/8d82143t