0
我有一個需要App_Data子文件夾的寫入權限的ASP.NET應用程序。用於部署應用程序的MSI嘗試正確設置權限,但儘管如此,看起來權限有時是錯誤的。沒有此許可,大部分應用程序都可以正常工作如果權限錯誤,我寧願應用程序啓動失敗。在啓動ASP.NET應用程序期間確保權限正確的最佳做法
確保IIS用戶環境所需權限正確的最佳做法是什麼?理想情況下,我想展示一些簡單的指導來解決任何錯誤。我希望消息出現在儘可能多的錯誤配置中。
以下描述了迄今爲止我所嘗試的,直到我意識到有可能是更好的或標準的方式。
我試圖把這個在Application_Start()
protected void Application_Start(Object sender, EventArgs e)
{
// Assert permissions on writeable folders are correct
var permissionsChecker = new AppDataPermissionsChecker();
permissionsChecker.AssertFolderIsWriteable(
HttpContext.Current.Server.MapPath("~/App_Data"));
// remainder of Application_Start()...
}
其中AppDataPermissionsChecker
定義如下:
public class AppDataPermissionsChecker
{
private bool CanWriteAccessToFolder(string folderPath)
{
try
{
// Attempt to get a list of security permissions from the folder.
// This will raise an exception if the path is read only or do not have access to view the permissions.
DirectorySecurity directorySecurity = Directory.GetAccessControl(folderPath);
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
public void AssertFolderIsWriteable(string folderPath)
{
if (!Directory.Exists(folderPath))
throw new Exception(String.Format("The {0} folder does not exist.", folderPath));
if (!CanWriteAccessToFolder(folderPath))
throw new Exception(String.Format("The ASPNET user does not have "
+ "access to the {0} folder. Please ensure the ASPNET user has "
+ "read/write/delete access on the folder. See 'The App_Data folder' "
+ "here: http://msdn.microsoft.com/en-us/library/06t2w7da.aspx'",
folderPath));
}
}
我認爲這將拋出一個醜陋異常,如果權限不正確(這是聊勝於無),但在某些情況下,我只是得到一個HTTP錯誤503.
如果在應用程序運行時權限發生了變化,該怎麼辦?在執行實際的App_Data寫入操作時,您仍然需要一種捕獲和顯示權限衝突異常的方法。 – 2012-07-16 12:39:34
@Kuba,在我的應用程序中,安裝後權限不太可能會發生變化,所以我更感興趣在第一次啓動時捕獲問題。 – shamp00 2012-07-16 13:12:41
呃......週末頭部受傷,睡眠不多,所以現在我有些模糊。但是,您可以通過定義所需的權限來修飾裝配的安全屬性。我現在不記得屬性名稱。我認爲它是[SecurityPermission()],然後看看屬性。 – 2012-07-16 14:05:27