我有一个网页,允许用户将文件上传到网络共享。当我在本地(在 VS 2008 中)运行网页并尝试上传文件时,成功了!但是,当我将网站部署到网络服务器并尝试通过网页上传文件时,它不起作用!
网络服务器返回给我的错误是“访问路径 '\05prd1\emp\test.txt' 被拒绝。所以,很明显,这是一个权限问题。
网络共享配置为允许对我(NT 身份验证)和网络服务(这是 .NET 的默认帐户以及我们在 IIS 应用程序池中设置为该网站的默认用户)的完全访问。
我已经在网络服务器上尝试过使用和不使用模拟,但两种方法都行不通,但两种方法都可以在我的本地计算机上运行(换句话说,使用和不使用模拟都可以在我的本地计算机上运行)。
上传文件的代码如下。请注意,下面的代码包含模拟,但正如我上面所说,我已经尝试过使用和不使用模拟,但没有任何区别。
if (fuCourses.PostedFile != null && fuCourses.PostedFile.ContentLength > 0) {
System.Security.Principal.WindowsImpersonationContext impCtx;
impCtx =
((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
try {
lblMsg.Visible = true;
// The courses file to be uploaded
HttpPostedFile file = fuCourses.PostedFile;
string fName = file.FileName;
string uploadPath = "\\\\05prd1\\emp\\";
// Get the file name
if (fName.Contains("\\")) {
fName = fName.Substring(
fName.LastIndexOf("\\") + 1);
}
// Delete the courses file if it is already on \\05prd1\emp
FileInfo fi = new FileInfo(uploadPath + fName);
if (fi != null && fi.Exists) {
fi.Delete();
}
// Open new file stream on \\05prd1\emp and read bytes into it from file upload
FileStream fs = File.Create(uploadPath + fName, file.ContentLength);
using (Stream stream = file.InputStream) {
byte[] b = new byte[4096];
int read;
while ((read = stream.Read(b, 0, b.Length)) > 0) {
fs.Write(b, 0, read);
}
}
fs.Close();
lblMsg.Text = "File Successfully Uploaded";
lblMsg.ForeColor = System.Drawing.Color.Green;
}
catch (Exception ex) {
lblMsg.Text = ex.Message;
lblMsg.ForeColor = System.Drawing.Color.Red;
}
finally {
impCtx.Undo();
}
}
如有任何帮助,我们将不胜感激!
最佳答案
您没有提及您在 IIS 中使用的身份验证类型。
如果您依赖 Windows Integrated/NTLM 身份验证,那么我认为您会遇到问题,除非您可以在服务器上配置 Kerberos,否则用户的身份验证 token 不能在当前(网络)服务器之外使用 - the “double-hop” 问题。
如果您使用 Basic(在 IIS 中)或 Forms(通过 ASP.NET),那么您将可以访问明文形式的用户密码。然后,您可以使用用户名/密码调用模拟代码,并且应该能够以该用户身份访问共享文件夹。
我也很确定,如果您使用基本身份验证,那么
查看知识库文章 306158也可获取更多信息和代码示例。
关于.NET 模拟和文件上传问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2547499/