你有一个有趣的问题,Null。您如何配置您的站点目录安全性?如果启用匿名访问,则对所有人开放的文件夹可能不允许访问,具体取决于服务器的操作系统(有关详细信息,请参阅 this Microsoft KB Article)。
如果站点以匿名方式运行,您可以更改站点在 IIS 管理器中运行的帐户,或者您可以启用模拟。当您在 Visual Studio 中运行该站点时,该站点正在使用您的权限运行,因此匿名不是问题。
您可以使用以下代码来输出您的网站正在运行的用户的身份,以帮助了解正在发生的事情。您可以让您的网站运行的用户无需任何模拟即可访问网络位置。为您的页面添加一个 ASP:Label 并查看您的运行身份:
lblSomeLabel.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name
模拟可能会给您带来额外的安全风险,因此您应该在进行更改之前多阅读一些内容 - 但是,您用于模拟的用户不需要是域管理员。在您的情况下,用户可能只需要对网络位置具有完全访问权限。
您可以阅读有关如何启用模拟on this Microsoft KB Article 的更多信息。下面是我推荐的该页面的一些代码。下面的代码不会让您的整个网站以模拟模式运行,而是仅运行您遇到问题的部分。
public void Page_Load(Object s, EventArgs e)
{
if(impersonateValidUser("username", "domain", "password"))
{
//Insert your code that runs under the security context of a specific user here.
undoImpersonation();
}
else
{
//Your impersonation failed. Therefore, include a fail-safe mechanism here.
}
}
private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if(RevertToSelf())
{
if(LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if(DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if(token!= IntPtr.Zero)
CloseHandle(token);
if(tokenDuplicate!=IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
private void undoImpersonation()
{
impersonationContext.Undo();
}
另外,在搜索安全文章时,我发现 this StackOverflow question 值得一读。