I don't know that this is possible exactly how you requested it. But, I do know of a way you can do this using a different method. Maybe it will work for you.
The idea is to store the secured files in a folder that is not available from the web (not a virtual directory). Then, have a method on a controller like Controllers/DownloadController.cs
that handles user authentication and file serving. Here's a sample method that can retrieve a file from c:\myfiles
:
Controllers/DownloadController.cs (action method only):
[Authorize]
public FileResult Download(string filename)
{
//get content type from file extension
var contentType = getContentTypeFromExtension(filename);
//return file with filename as third argument to
// trigger browser's download bahavior
return File(Path.Combine(fileFolder, filename), contentType, filename);
}
[Authorize]
public FileResult Open(string filename)
{
//get content type from file extension
var contentType = getContentTypeFromExtension(filename);
//return file without download filename so that
// the file is opened in browser (if possible)
return File(Path.Combine(fileFolder, filename), contentType);
}
//method to get content type of file from registry using file extension
static string getContentTypeFromExtension (string fileName)
{
string contentType = "application/unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
contentType = regKey.GetValue("Content Type").ToString();
return contentType;
}
fileFolder
variable should be defined at the class level. I took it out because it was messing with the code formatting. :)