1. 在项目下新建一个文件夹来专门放过滤器类,首先创建一个类LoginFilter,这个类继承ActionFilterAttribute。用来检查用户是否登录和用户权限。:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;namespace weixinmenu.Filter
{/// <summary>/// 这个过滤器类继承ActionFilterAttribute/// </summary>public class LoginFilterAttribute:ActionFilterAttribute{/// <summary>/// 改写onactionexecuting(在controller action执行之前调用),去判断请求中是不是存了session。使用场景:如何验证登录等。/// </summary>/// <param name="filterContext"></param>public override void OnActionExecuting(ActionExecutingContext filterContext){if (HttpContext.Current.Session["UserName"] == null){HttpContext.Current.Response.Write("<script>alert('请先登录');window.parent.location.href='/Users/Login'</script>");}//这种是通过返回一段js代码来实现跳转登录页面//if (filterContext.HttpContext.Session["UserName"] == null)//{//    filterContext.HttpContext.Response.Redirect("/Users/Login");//}//这种就是直接通过过滤器上下文的的http上下文请求来进行重置链接
        }/// <summary>/// 在Action方法调用后,result方法调用前执行,使用场景:异常处理。/// </summary>/// <param name="filterContext"></param>public override void OnActionExecuted(ActionExecutedContext filterContext){//  base.OnActionExecuted(filterContext);
        }/// <summary>/// 在result执行前发生(在view 呈现前),使用场景:设置客户端缓存,服务器端压缩./// </summary>/// <param name="filterContext"></param>public override void OnResultExecuting(ResultExecutingContext filterContext){//base.OnResultExecuting(filterContext);
        }/// <summary>/// 在result执行后发生,使用场景:异常处理,页面尾部输出调试信息。/// </summary>/// <param name="filterContext"></param>public override void OnResultExecuted(ResultExecutedContext filterContext){//  base.OnResultExecuted(filterContext);
        }}
}

2.页面程序,也就是控制器里的程序,如下

LoginFilter是扩展属性,自定义属性名称是根据上面的LoginFilterAttribute名变化而来

当程序走controller/action时,会先走这个自定义特性LoginFilter再走action的。

[Filter.LoginFilter]public class WxMenuController : Controller{// GET: WxMenu
WeixinMenuBusiness weixinMenuBusiness = new WeixinMenuBusiness();public ActionResult Index(){NHibernateHelper nhlper = new NHibernateHelper();ISession session = nhlper.GetSession();IEnumerable<WeiXinMenu> kinds = session.Query<WeiXinMenu>();WeiXinMenu root = kinds.FirstOrDefault(c => c.ParentId == "-1");ViewBag.root = kinds;return View(root);}public ActionResult Menu(){System.Web.HttpContext curContext = System.Web.HttpContext.Current;if (curContext.Session["UserName"] != null){ViewBag.UserName = curContext.Session["UserName"].ToString();}return View();}/// <summary>/// 返回查询到的菜单json/// </summary>/// <param name="page"></param>/// <param name="rows"></param>/// <param name="sort"></param>/// <param name="order"></param>/// <returns></returns>public ActionResult MenuGridView(int? page, int? rows, string sort = "", string order = "asc"){return Content(GetMenuGridTree());}public string GetMenuGridTree(){NHibernateHelper nhlper = new NHibernateHelper();ISession session = nhlper.GetSession();List<TreeModel> result = new List<TreeModel>();List<TreeModel> children = new List<TreeModel>();IEnumerable<WeiXinMenu> kinds = session.Query<WeiXinMenu>();WeiXinMenu root = kinds.FirstOrDefault(c => c.ParentId == "-1");GetMenuGridTree(kinds, children, "10000");result.Add(new TreeModel{Id = root.Id.ToString(),MenuId = root.MenuId,Text = root.MenuName,Url = root.MenuUrl,ParentMenuId = root.ParentId.ToString(),IsEnable = root.IsEnable,OrderBy = root.OrderBy.ToString(),Target = root.MenuType,Ico = root.MenuKey,children = children});return JsonConvert.SerializeObject(result);}private void GetMenuGridTree(IEnumerable<WeiXinMenu> kinds, List<TreeModel> children, string pId){foreach (WeiXinMenu p in kinds.Where(c => c.ParentId == pId).OrderBy(c => c.OrderBy)){TreeModel gt = new TreeModel();gt.Id = p.Id.ToString();gt.MenuId = p.MenuId;gt.Text = p.MenuName;gt.Url = p.MenuUrl;gt.ParentMenuId = p.ParentId;gt.IsEnable = p.IsEnable;gt.OrderBy = p.OrderBy.ToString();gt.Target = p.MenuType;gt.Ico = p.MenuKey;List<TreeModel> childrenTmp = new List<TreeModel>();GetMenuGridTree(kinds, childrenTmp, p.MenuId);/*if (childrenTmp.Count > 0){gt.state = "closed";}*/gt.children = childrenTmp;children.Add(gt);}}public JsonResult MenuToWeiXin(){try{MenuManager.CreateMenu();return Json(new { Success = true, Message = "请求成功" });}catch (Exception ex){return Json(new { Success = false,Message = ex.Message });}}/// <summary>/// 保存更新操作/// </summary>/// <param name="model"></param>/// <returns></returns>public JsonResult MenuSaveOrUpdate(WeiXinMenu model){try{NHibernateHelper nhlper = new NHibernateHelper();ISession session = nhlper.GetSession();session.SaveOrUpdate(model);session.Flush();return Json(new { Success = true,Message = "保存成功"});}catch (Exception ex){return Json(new { Success=false,Message = ex.Message});}}/// <summary>/// 菜单删除函数/// </summary>/// <param name="ids"></param>/// <returns></returns>public JsonResult MenuDelete(string ids){try{NHibernateHelper nhlper = new NHibernateHelper();ISession session = nhlper.GetSession();string[] idss= ids.Split('\'');string idsss = idss[1];int id = int.Parse(idsss);WeiXinMenu tmpentites = session.Get<WeiXinMenu>(id);session.Delete(tmpentites);session.Flush();return Json(new { Success = true,Message = "删除成功"});}catch (Exception ex){return Json(new { Success=false,Message = ex.Message});}}/// <summary>/// 菜单编辑函数/// </summary>/// <param name="id"></param>/// <returns></returns>public ActionResult MenuEdit(int id){NHibernateHelper nhlper = new NHibernateHelper();ISession session = nhlper.GetSession();WeiXinMenu model = session.Get<WeiXinMenu>(id);if (model == null){model = new WeiXinMenu();model.IsEnable = "1";model.CreateTime = DateTime.Now;}return View(model);}public ActionResult MenuTree(){string ids = Request["ids"];List<string> data = new List<string>();if (ids.IsNotNull()){data = ids.ToStrList(',');}return Content(GetMenuComboTree(data));}public static string GetMenuComboTree(List<string> data){NHibernateHelper nhlper = new NHibernateHelper();ISession session = nhlper.GetSession();List<ComboTree> result = new List<ComboTree>();List<ComboTree> children = new List<ComboTree>();IEnumerable<WeiXinMenu> kinds = session.Query<WeiXinMenu>();WeiXinMenu root = kinds.FirstOrDefault(c => c.ParentId == "-1");GetMenuComboTree(kinds, children, root.MenuId, data);result.Add(new ComboTree{id = root.MenuId.ToString(),text = root.MenuName,@checked = false,children = children});return JsonConvert.SerializeObject(result);}public static void GetMenuComboTree(IEnumerable<WeiXinMenu> kinds,List<ComboTree> children, string pId, List<string> data){foreach (WeiXinMenu p in kinds.Where(c => c.ParentId == pId).OrderBy(c => c.OrderBy)){ComboTree gt = new ComboTree();gt.id = p.MenuId;gt.text = p.MenuName;List<ComboTree> childrenTmp = new List<ComboTree>();GetMenuComboTree(kinds, childrenTmp, p.MenuId, data);gt.children = childrenTmp;if (childrenTmp.Count == 0 && data.Contains(p.Id.ToString())){gt.@checked = true;}else{gt.@checked = false;}children.Add(gt);}}}

View Code

3.在登录时存Session的操作:

在验证用户输入的用户名和密码都是正确之后。把用户名存到Session中去。 Session["UserName"] = UserName;

ps:

在每次重新生成项目在时候,session 会过期,在 web.config 修改一下 session 配置,把session改成存在单线程里面即可解决。

web.config:

<system.web>  <sessionState mode="StateServer" timeout="30"></sessionState>
</system.web>  

推荐一个比较好的讲相关内容的博客:http://blog.csdn.net/u010096526/article/details/46700581

一个MVC系列的博客:http://www.cnblogs.com/P_Chou/archive/2010/11/01/details-asp-net-mvc-content.html

转载于:https://www.cnblogs.com/jackcheblog/p/7094769.html

MVC学习笔记:MVC实现用户登录验证ActionFilterAttribute用法并实现统一授权相关推荐

  1. Linux学习笔记(四)之用户登录

    1.Linux是一个网络操作系统,作为多用户,多任务的操作系统,其系统资源是所有用户共享的.任何要使用系统资源者必须先在系统内登记,注册,即开设用户账号,该账号又包含用户名,口令,所用的shell,使 ...

  2. 【CS学习笔记】17、登录验证的难点

    0x00 前言 如果当前账号权限被系统认为是本地管理员权限,那么就可以执行很多管理员才能做的事,接下来就来看一下这样的一个过程是如何工作的,其中会涉及到以下要点: 1.Access Token 登录令 ...

  3. sqlplus普通用户登录oracle,Oracle学习笔记:sqlplus用户登录

    1 sqlplus 登录 本地登录 (登录数据库服务器) Oracle 登录 sqlplus 账户名/密码 as 角色名 1.1 sys登录 例如: sqlplus sys/or 1 sqlplus ...

  4. 尚硅谷谷粒学院学习笔记9--前台用户登录,注册,整合jwt,微信登录

    用户登录业务 单点登录(Single Sign On),简称SSO. 用户只需要登陆一次就可以访问所有相互信任的应用系统 单点登录三种常见方式 session广播机制实现 使用redis+cookie ...

  5. Spring MVC 学习笔记 对locale和theme的支持

    Spring MVC 学习笔记 对locale和theme的支持 Locale Spring MVC缺省使用AcceptHeaderLocaleResolver来根据request header中的 ...

  6. .NET MVC 学习笔记(一)— 新建MVC工程

    一..NET MVC 学习笔记(一)-- 新建MVC工程 接触MVC有段时间了,一直想找机会整理一下,可是限于文笔太差,所以一直迟迟羞于下手,想到最近做过的MVC项目也有一些了,花点时间整理一下方便以 ...

  7. Spring MVC 学习笔记一 HelloWorld

    Spring MVC 学习笔记一 HelloWorld Spring MVC 的使用可以按照以下步骤进行(使用Eclipse): 加入JAR包 在web.xml中配置DispatcherServlet ...

  8. html登录验证功能,续:实现用户登录验证功能

    一.提纲 1.Previously前情提要 已经把Thymeleaf部署到项目中: 把前端开发的静态资源成功引入到项目中: 完成登录验证功能,登录成功跳转到success.html页面,登录失败跳转到 ...

  9. python登录验证程序_Python模拟用户登录验证

    本文实例为大家分享了Python模拟用户登录验证的具体代码,供大家参考,具体内容如下 1.功能简介 此程序模拟用户登录验证的过程,实现用户名输入.黑名单检测.用户有效性判别.密码输入及验证等.用户在3 ...

  10. php链接mysql实例之用户登录验证以及使用cookie登录

    这篇博客实现用户登录验证以及使用cookie登录,它承接了前面的几个博客: 1. php连接mysql实例之新用户注册实现 2. php连接mysql实例之后台列表显示已注册的用户信息 3. php连 ...

最新文章

  1. Activiti工作流内建数据库表分析
  2. Want to archive tables? Use Percona Toolkit’s pt-archiver--转载
  3. Python中的一些“小坑”
  4. 怎么给mysql用户添加权限_MySQL下添加用户以及给予权限的实现
  5. 读书印记 - 《异类:不一样的成功启示录》
  6. vue中el-row使用
  7. python内容限制_Python --类,实例和访问限制
  8. 接口测试工具 soapui 下载及安装
  9. 归并排序java详解
  10. C#实现的简单的随机抽号器
  11. python项目:基于OpenCV的学生网课睡意检测系统
  12. 千峰商城-springboot项目搭建-06-数据库创建
  13. “高定美学”品牌矩阵:「莲玉芳华」「琢我」「佐我」佐我气运系列之进击
  14. CoreOS容器云企业实战(3)--Docker技术实践
  15. Jsp实现注册登录以及忘记找回密码等操作(上)
  16. pytorch 中 利用自定义函数 get_mask_from_lengths(lengths, max_len)获取每个batch的mask
  17. 星巴克推出首个黄金档嘉宾“夜聊”节目;阿华田中国首发两款新品;帝亚吉欧中国首家麦芽威士忌酒厂正式动工 | 食品饮料新品...
  18. BZOJ 3238 [Ahoi2013]差异
  19. 关于计算机缺少vcruntime140_1.dll的下载修复解决方案
  20. 服务器bcd配置损坏怎么修复,引导记录损坏修复方法详解

热门文章

  1. R语言之数据分析高级方法「时间序列」
  2. Winsock编程入门 -- 4.面向连接的通讯
  3. Spring IOC的三种主要注入方式?
  4. JAVA多线程之synchronized和volatile实例讲解
  5. Android---06---2中动画效果
  6. WIFEXITED WEXITSTATUS WIFSIGNALED(转)
  7. TF400511: Your team has not defined any iterations to use as sprints
  8. Spring @Aspect实现切面编程
  9. android中的四种基本动画
  10. 多普达,D600,Coreplayer可用的序列号(版本未查看)。