【发布时间】:2012-07-15 07:14:20
【问题描述】:
我有一个 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。
【问题讨论】:
-
如果应用程序运行时权限发生变化怎么办?在执行实际的 App_Data 写入操作时,您仍然需要一种方法来捕获和显示权限冲突异常。
-
@Kuba,在我的应用程序中,安装后权限不太可能发生变化,所以我更有兴趣在首次启动时发现问题。
-
嗯……周末头部受伤,睡眠不足,所以我现在有点模糊。但是有一些安全属性,您可以通过定义所需的权限来装饰您的程序集。我现在不记得属性名称了。我认为是[SecurityPermission()] 然后看属性。
标签: c# asp.net security permissions