.NET MVC 通过权限控制文件的下载

一. 配置Web.config(需要IIS服务器已安装请求筛选模块)

<security>

      <requestFiltering>

        <fileExtensions>

        <add fileExtension=".txt" allowed="false" />

        <add fileExtension=".exe" allowed="false" />

        </fileExtensions>

      </requestFiltering>

    </security>

二. 添加测试文件夹

三. Download 主代码

public class DownloadController : BaseController

    {

        [Authorize]

        public ActionResult DownloadFile(string name)

        {

            if (string.IsNullOrEmpty(name))

            {

                return Json("File name is required, download failed!", JsonRequestBehavior.AllowGet);

            }

            string[] arr = name.Split('.');

            if (arr.Length < 2)

            {

                return Json("File name format is wrong, download failed!", JsonRequestBehavior.AllowGet);

            }

            string path = Server.MapPath("/Downloads" + "/" + name);

            if (System.IO.File.Exists(path) == false)

            {

                return Json("File is not exist, download failed!", JsonRequestBehavior.AllowGet);

            }


            return File(new FileStream(path, FileMode.Open), "application/octet-stream", name);

        }

    }

四、测试结果:





http://localhost:55215/download/downloadfile?name=test.txt 正常下载

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,516评论 19 139
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,151评论 0 13
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,744评论 0 38
  • 记录昨天的一手牌。后卫59同花,前面limp两家,我也limp。 最后共六家limp。翻牌559。我揉了揉眼睛,再...
    舍德君阅读 4,814评论 0 0
  • 生活中,“我”和“你”发生了好多故事,也许你会觉得我善解人意,特别愿意和我相处。也许会觉得我咄咄逼人,真想一脚把...
    冰小夏阅读 1,456评论 0 4