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

2018-11-15  本文已影响15人  Jason_兵哥

一. 配置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 正常下载

上一篇下一篇

猜你喜欢

热点阅读