Question

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;
}

I'm not interested in a code review, I know things could be done better. Right now I've hit an unusual problem. StaticContentPath points to c:\inetpub\wwwroot\static.domain.com, which is being served by a different application pool which is configured to disable scripting and cache things heavier. If I manually place a file in the static content folder, it will serve correctly. If the above code (from a different application pool) saves a file there, the permissions are very unusual. I'll attach screenshots.

The "default" file is one I pasted manually. It properly inherited permissions from the parent folder. The hashed filename was saved by the above code, and it does not inherit permissions properly. When I attempt to access the file, I get a very basic error message from IIS, the entirety of which is "The page cannot be displayed because an internal server error has occurred." No styling, nothing I'm used to seeing with IIS errors. If I manually add read permissions to the IIS_IUSRS account everything works as I'd expect.

Why is this happening, what can I do to mitigate it, and does my code need to be updated?

Good permissions Bad permissions Good advancedBad advanced

Was it helpful?

Solution

I suspect the problem is with the use of Path.GetTempFileName followed by File.Move. When the uploaded file is saved to tempFilename, the temporary file gets whatever permissions are assigned to the temporary folder. Moving the file preserves those permissions as is instead of recalculating the inheritable permissions based on the destination.

Instead of File.Move, try using File.Copy followed by File.Delete:

//File.Move(tempFilename, destinationFilename);
File.Copy(tempFilename, destinationFilename);
File.Delete(tempFilename);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top