简体   繁体   English

限制.xml文件和.cs文件的下载范围

[英]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. 现在,如果有人手动更改查询字符串中的文件名(如web.config),则它还会下载配置文件。

So please share your knowledge how to restrict from download based on file extension. 因此,请分享您的知识,以及如何限制基于文件扩展名的下载。

That is usually done in IIS. 这通常是在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. Web服务器本身可以很好地处理文件下载并防止访问不应共享的文件。

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. 然后,Web服务器仍将首先确定权限和其他内容,以防止恶意用户下载敏感文件,并且如果允许,您的代码将在下载之前运行。

That being said, you don't want to serve files for download from your web root. 话虽如此,您不想提供从Web根下载的文件。 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 \\ ). 然后使用filename = Path.GetFileName(filename)防止用户导航到该目录之外(使用..和/或\\ )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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