我有一个 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。