开发者

Error in file download using ASP MVC3

开发者 https://www.devze.com 2023-03-26 06:59 出处:网络
This code is supposed to download a file usingmvc3 controller public FilePathResult GetFileFromDisk(String file)

This code is supposed to download a file using mvc3 controller

public FilePathResult GetFileFromDisk(String file)
{
     String path = AppDomain.CurrentDomain.BaseDirectory + "AppData/";
     String contentType = "text/plain";
     return File(path+file, contentType, file);
}

View part :

@Html.ActionLink("Download", "GetFileFromDisk","Upload", new { file = "textfile" },null);

But when i click the link I am getting this error

Could not find a part of the path 'D:\Project\FileUploadDownload\FileUploadDownload\AppData\textfile'.

[DirectoryNotFoundException: Could not find a part of the path 'D:\Project\FileUploadDo开发者_Python百科wnload\FileUploadDownload\AppData\textfile'.]

Why the foldername is repeating in the file path? Please offer a solution...


Try like this:

public ActionResult GetFileFromDisk(string file)
{
    var appData = Server.MapPath("~/App_Data");
    var path = Path.Combine(appData, file);
    path = Path.GetFullPath(path);
    if (!path.StartsWith(appData))
    {
        // Ensure that we are serving file only inside the App_Data folder
        // and block requests outside like "../web.config"
        throw new HttpException(403, "Forbidden");
    }

    if (!System.IO.File.Exists(path))
    {
        return HttpNotFound();
    }

    var contentType = "text/plain";
    return File(path, contentType, Path.GetFileName(path));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消