美文网首页
.NET MVC 通过权限控制文件的下载

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

作者: Jason_兵哥 | 来源:发表于2018-11-15 14:27 被阅读15次

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

相关文章

网友评论

      本文标题:.NET MVC 通过权限控制文件的下载

      本文链接:https://www.haomeiwen.com/subject/ulhyfqtx.html