[英]Why are permissions wonky when my IIS worker saves a file in ASP.NET?
IIS 8、ASP.NET MVC 4、.NET 4.5
private static string SaveProfilePicFile(UserProfileViewModel model)
{
var tempFilename = Path.GetTempFileName();
model.ProfilePic.Profile.UploadedFile.SaveAs(tempFilename);
var staticContentFilename = Helpers.GetStaticContentFilename(
StaticContentType.Avatar, model.ProfilePic.Profile.UserId);
var destinationFilename = Path.Combine(
ConfigurationManager.AppSettings["StaticContentPath"],
"profile",
staticContentFilename);
if (File.Exists(destinationFilename))
File.Delete(destinationFilename);
if (!HasJpegHeader(tempFilename)) // convert temp file into JPG
{
using (var image = new Bitmap(tempFilename))
image.Save(destinationFilename, ImageFormat.Jpeg);
File.Delete(tempFilename);
}
else
{
File.Move(tempFilename, destinationFilename);
}
return staticContentFilename;
}
我對代碼審查不感興趣,我知道事情可以做得更好。 現在我遇到了一個不尋常的問題。 StaticContentPath
指向c:\\inetpub\\wwwroot\\static.domain.com
,它由不同的應用程序池提供服務,該應用程序池配置為禁用腳本並緩存更重的內容。 如果我手動將文件放在靜態內容文件夾中,它將正確提供。 如果上面的代碼(來自不同的應用程序池)在那里保存了一個文件,則權限非常不尋常。 我會附上截圖。
“默認”文件是我手動粘貼的文件。 它從父文件夾正確繼承了權限。 散列文件名是由上面的代碼保存的,它沒有正確繼承權限。 當我嘗試訪問該文件時,我從 IIS 收到一條非常基本的錯誤消息,整個錯誤消息是“頁面無法顯示,因為發生了內部服務器錯誤”。 沒有樣式,我不習慣看到 IIS 錯誤。 如果我手動向 IIS_IUSRS 帳戶添加讀取權限,一切都會如我所願。
為什么會發生這種情況,我可以做些什么來緩解它,我的代碼是否需要更新?
我懷疑問題在於使用Path.GetTempFileName
后跟File.Move
。 當上傳的文件保存到tempFilename
,臨時文件將獲得分配給臨時文件夾的任何權限。 移動文件會按原樣保留這些權限,而不是根據目標重新計算可繼承的權限。
而不是File.Move
,嘗試使用File.Copy
后跟File.Delete
:
//File.Move(tempFilename, destinationFilename);
File.Copy(tempFilename, destinationFilename);
File.Delete(tempFilename);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.