我不知道这是可能的,你究竟是如何要求它。但是,我知道你可以用不同的方法做到这一点。也许它会为你工作。
的想法是受保护的文件存储,是不是可以从网络(而不是虚拟目录)的文件夹。然后,在处理用户身份验证和文件服务的控制器(如Controllers/DownloadController.cs
)上有一个方法。下面是可以从c:\myfiles
检索文件的样品的方法:
控制器/ DownloadController.cs(动作仅法):
[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
变量应在类级别来定义。我把它拿出来,因为它搞乱了代码格式。 :)
有趣。我想避免使用处理程序,但这可能是我唯一的选择。有一个问题,当返回的“文件”是图像时,它是否会在浏览器中打开,就好像用户点击了图像,或者是否开始下载图像作为下载内容一样。我希望前者。谢谢。 – kmehta 2010-07-27 20:31:33
如果您希望它像下载一样行事,只需将第三个参数添加到返回文件(...)行。我会更新代码来举例。 – 2010-07-27 20:36:54
谢谢!我会给这个镜头。 – kmehta 2010-07-27 20:42:35