c# - 当我的 IIS 工作人员在 ASP.NET 中保存文件时,为什么权限不稳定?

标签 c# asp.net iis permissions ntfs

IIS 8、ASP.NET MVC 4、.NET 4.5

private static string SaveProfilePicFile(UserProfileViewModel model)
{
    var tempFilename = Path.GetTempFileName();

    model.ProfilePic.Profile.UploadedFile.SaveAs(tempFilename);

    var staticContentFilename = Helpers.GetStaticContentFilename(
        StaticContentType.Avatar, model.ProfilePic.Profile.UserId);

    var destinationFilename = Path.Combine(
        ConfigurationManager.AppSettings["StaticContentPath"],
        "profile",
        staticContentFilename);

    if (File.Exists(destinationFilename))
        File.Delete(destinationFilename);

    if (!HasJpegHeader(tempFilename)) // convert temp file into JPG
    {
        using (var image = new Bitmap(tempFilename))
            image.Save(destinationFilename, ImageFormat.Jpeg);

        File.Delete(tempFilename);
    }
    else
    {
        File.Move(tempFilename, destinationFilename);
    }

    return staticContentFilename;
}

我对代码审查不感兴趣,我知道事情可以做得更好。现在我遇到了一个不寻常的问题。 StaticContentPath 指向 c:\inetpub\wwwroot\static.domain.com,它由不同的应用程序池提供服务,该应用程序池配置为禁用脚本并缓存较重的内容。如果我手动将文件放入静态内容文件夹中,它将正确运行。如果上面的代码(来自不同的应用程序池)在那里保存文件,则权限非常不寻常。我将附上屏幕截图。

“默认”文件是我手动粘贴的。它正确地继承了父文件夹的权限。上面的代码保存了散列文件名,它没有正确继承权限。当我尝试访问该文件时,我从 IIS 收到一条非常基本的错误消息,其全部内容是“由于发生内部服务器错误,无法显示该页面”。没有样式,没有任何我习惯看到的 IIS 错误。如果我手动向 IIS_IUSRS 帐户添加读取权限,一切都会按我的预期进行。

为什么会发生这种情况,我可以采取什么措施来缓解这种情况,以及我的代码是否需要更新?

Good permissions Bad permissions Good advanced Bad advanced

最佳答案

我怀疑问题出在使用 Path.GetTempFileNameFile.Move 上。当上传的文件保存到 tempFilename 时,临时文件将获得分配给临时文件夹的任何权限。移动文件会按原样保留这些权限,而不是根据目标重新计算可继承权限。

尝试使用File.Copy,然后使用File.Delete,而不是File.Move:

//File.Move(tempFilename, destinationFilename);
File.Copy(tempFilename, destinationFilename);
File.Delete(tempFilename);

关于c# - 当我的 IIS 工作人员在 ASP.NET 中保存文件时,为什么权限不稳定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23136723/

相关文章:

c# - 是否有 ListDictionary 类的通用替代品?

c# - 从 C# 中读取 XML

asp.net - 如何在运行时重写 Web Config 连接字符串

php - PHP 使用 mysqli_connect 时出现服务器超时/登录错误

web-services - 来自 ColdFusion 8 的未经授权的 Sharepoint WSDL

c# - 使用集合的 Azure 移动服务查询包含

c# - 使用 EPPlus 创建的 Excel 图表中的图例颜色不正确

asp.net - 如何在JQuery中使用ajax

asp.Net MVC View 模型在帖子中为空

php - 在 IIS 上托管 Wordpress 时建立数据库连接时出错