简体   繁体   中英

Restrict .xml file and .cs file from download

In one of project i saw the below code.

        string FileName = Request.QueryString["filename"];
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "application/octet-stream";
        response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
        response.TransmitFile(Server.MapPath("~/" + FileName));
        response.Flush();
        response.End();

which is used to download file from server. Now if someone changes filename (like web.config) in query string manually then it downloads config file also.

So please share your knowledge how to restrict from download based on file extension.

That is usually done in IIS. But, if you wanna to it programmatically:

string[] forbiddenExtensions = new string[] {".config", ".abc", ".xml" };
FileInfo fi = new FileInfo(FileName);
if (forbiddenExtensions.Contains(fi.Extension))
{
    //throw some error or something...
}

First of all, you'll have to ask yourself whether you want to write code to let users download files present on the file system. The web server itself is perfectly fine handling file downloads and preventing access to files that shouldn't be shared.

If you're sure you want to do this, for example because you want some code to run before every download, then you should look at creating a handler instead. Then the web server will still first determine permissions and whatnot, in order to prevent malicious users from downloading sensitive files, and when allowed, your code will run before the download.

That being said, you don't want to serve files for download from your web root. Instead create a dedicated directory, say, "Downloads", and host your files for download from there. Then use filename = Path.GetFileName(filename) to prevent the user from navigating outside that directory (using .. and/or \\ ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM