MVC 自定义过滤器和设置文件夹作为下载文件夹
1.自定义登录验证的过滤器(用seesion保存用户名,不用数据库)
1 /// <summary> 2 /// 登录验证 3 /// </summary> 4 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 5 public class AuthAttribute : ActionFilterAttribute 6 { 7 public override void OnActionExecuting(ActionExecutingContext filterContext) 8 { 9 var c = filterContext.Controller as Controller; 10 if (filterContext.HttpContext.Session["UserName"] == null || string.IsNullOrWhiteSpace(filterContext.HttpContext.Session["UserName"].ToString()) == true) 11 { 12 //Session 不存在则跳回登录界面 13 filterContext.Result = new RedirectResult("~/Home/UserLogin"); 14 } 15 base.OnActionExecuting(filterContext); 16 } 17 }
2.验证登录,写入seesion
1 /// <summary> 2 /// 验证登录 3 /// </summary> 4 /// <param name="model"></param> 5 /// <returns></returns> 6 [HttpPost] 7 [ValidateAntiForgeryToken] 8 public ActionResult UserLogin(LoginModel model) 9 { 10 if (ModelState.IsValid) 11 { 12 string userName = model.UserName; 13 string password = model.Password; 14 if (userName == "kapu" && password == "hugeclaw") 15 { 16 HttpContext.Session["UserName"] = userName; 17 return RedirectToAction("DownloadList", "Home"); 18 } 19 } 20 ModelState.AddModelError("", "提供的用户名或密码不正确。"); 21 return View(model); 22 }
3.引用过滤器,设置下载文件夹
1 /// <summary> 2 /// 下载列表 3 /// </summary> 4 /// <param name="isLogin"></param> 5 /// <returns></returns> 6 [Auth] 7 public ActionResult DownloadList() 8 { 9 Dictionary<string, string> file = new Dictionary<string, string>(); 10 var files = Directory.GetFiles(@"D:\myweb\download"); 11 foreach (var f in files) 12 { 13 file.Add(@"D:\myweb\download\" + Path.GetFileName(f), Path.GetFileName(f)); 14 } 15 ViewBag.file = file; 16 return View(); 17 }
4.开始下载
1 /// <summary> 2 /// 开始下载 3 /// </summary> 4 /// <param name="path"></param> 5 /// <returns></returns> 6 [Auth] 7 public ActionResult Download(string path) 8 { 9 var name = Path.GetFileName(path); 10 return File(path, "application/zip-x-compressed", name); 11 }
view:
1.登录页面
1 @model MVCDownloadTest.Models.LoginModel 2 @{ 3 ViewBag.Title = "登录"; 4 } 5 6 @using (Html.BeginForm("UserLogin", "Home", FormMethod.Post)) 7 { 8 @Html.ValidationSummary(true) 9 @Html.AntiForgeryToken() 10 <fieldset> 11 <legend>登录</legend> 12 <ol> 13 <li> 14 @Html.LabelFor(m => m.UserName) 15 @Html.TextBoxFor(m => m.UserName) 16 </li> 17 <li></li> 18 <li> 19 @Html.LabelFor(m => m.Password) 20 @Html.PasswordFor(m => m.Password) 21 </li> 22 </ol> 23 <input type="submit" value="登录" /> 24 </fieldset> 25 }
2.下载列表页面
1 @{ 2 ViewBag.Title = "下载列表"; 3 } 4 5 @foreach (var item in ViewBag.file) 6 { 7 <a href="@Href("~/Home/Download?path=" + item.Key)">@item.Value</a><br /> 8 }
注:详细demo在QQ微云->学习demo->MVCDownloadTest.rar

浙公网安备 33010602011771号