2013-02-02 47 views
0

我有這樣的:返回FilePath的Action方法不能正常工作。爲什麼?

[AllowAnonymous] 
public FilePathResult GetImage(string user) 
{ 
    var path = AppDomain.CurrentDomain.BaseDirectory + "files\\uploads\\users\\" + user + "\\avatar\\"; 
    var ext = this.GetImageExtension(path, user); 
    return ext != null ? File(path + user + "." + ext, "image/" + ext, user + "." + ext) : File(AppDomain.CurrentDomain.BaseDirectory + "files\\commonFiles\\users\\avatar\\noavatar.png", "image/png", "noavatar.png"); 
} 

而我的觀點裏我有這樣的:

<img src="/MyAccount/GetImage/[email protected]" 
    alt="@User.Identity.Name" /> 

現在,每當我用這個我的web開發者服務器內它的工作原理完全確定。但是,當我在我的服務器上發佈我的網站時,它甚至不試圖實施該操作。爲什麼?

回答

7

爲什麼?

因爲你硬編碼的URL到控制器的行動,而不是使用網址幫手:

<img src="@Url.Action("GetImage", "MyAccount", new { user = User.Identity.Name })" alt="@User.Identity.Name" /> 

你不應該硬編碼的URL中的ASP.NET MVC應用程序,但經常使用的網址助手。

同時將當前登錄的用戶作爲查詢字符串參數傳遞看起來像一個可怕的安全問題。沒有什麼能夠阻止用戶傳遞他喜歡的任何用戶名,並且諮詢該用戶的圖像。您應該在控制器操作中讀取當前經過身份驗證的用戶。

因此,通過擺脫這個查詢字符串參數的開始:

<img src="@Url.Action("GetImage", "MyAccount")" alt="@User.Identity.Name" /> 

,然後在你的控制器動作,您可以隨時檢索當前登錄的用戶與User.Identity.Name屬性:

[Authorize] 
public FilePathResult GetImage() 
{ 
    string user = User.Identity.Name; 
    var path = Server.MapPath(
     string.Format("~/files/uploads/users/{0}/avatar/", user) 
    ); 
    var ext = this.GetImageExtension(path, user); 
    if (string.IsNullOrEmpty(ext)) 
    { 
     return File(
      Server.MapPath("~/files/commonFiles/users/avatar/noavatar.png"), 
      "image/png", 
      "noavatar.png" 
     ); 
    } 
    var file = Path.ChangeExtension(Path.Combine(path, user), ext); 
    return File(file, "image/" + ext, user + "." + ext); 
} 

我我們還用[Authorize]屬性對此控制器操作進行了修飾,以使其僅對已通過身份驗證的用戶可訪問。如果這不是你的情況,你仍然可以保持[AllowAnonymous]屬性,但在嘗試訪問他的用戶名之前檢查User.Identity.IsAuthenticated

+0

事實上,問題是,因爲我很笨 - 當我發佈這個網站時,它並沒有複製我所有的工作目錄 - 而且它已經崩潰了。反正你的評論很棒,我也錯過了。謝謝! – ojek

+0

我也更新了我的答案,以包含有關在查詢字符串中傳遞當前登錄用戶名的信息,這是一個非常糟糕的主意。 –

相關問題