我有一个ASP.NET应用程序,需要在App_Data子文件夹上进行写访问。用于部署应用程序的MSI尝试正确设置权限,但尽管如此,似乎权限有时是错误的。未经此许可,大部分应用程序都可正常运行。如果权限错误,我希望应用程序无法启动。
确保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。