MVC学习笔记:MVC实现用户登录验证ActionFilterAttribute用法并实现统一授权
- 在项目下新建一个文件夹来专门放过滤器类,首先创建一个类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, "");
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[];
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 = "";
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 == && data.Contains(p.Id.ToString()))
{
gt.@checked = true;
}
else
{
gt.@checked = false;
}
children.Add(gt);
}
} }
3.在登录时存Session的操作:
在验证用户输入的用户名和密码都是正确之后。把用户名存到Session中去。 Session["UserName"] = UserName;
ps:
在每次重新生成项目在时候,session 会过期,在 web.config 修改一下 session 配置,把session改成存在单线程里面即可解决。
web.config:
<system.web>
<sessionState mode="StateServer" timeout=""></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
MVC学习笔记:MVC实现用户登录验证ActionFilterAttribute用法并实现统一授权的更多相关文章
- Spring MVC学习笔记——完整的用户登录
1.搭建环境的第一步是导包,把下面这些包都导入工程中 /media/common/工作/Ubuntu软件/SpringMVC_jar包整理/aop/media/common/工作/Ubuntu软件/S ...
- 前端MVC学习笔记(二)——AngularJS验证、过滤器、指令
一.验证 angularJS中提供了许多的验证指令,可以轻松的实现验证,只需要在表单元素上添加相应的ng属性,常见的如下所示: <input Type="text" ng-m ...
- ASP.NET MVC学习笔记(二)登陆验证
书上的验证时在配置文件中直接声明用户名和密码,想改成从数据验证账号和密码,搞了一下午都没高出来,不断的调试,发现 var table = userInfo.Tables.FirstOrDefault( ...
- MVC学习笔记---MVC的处理管线
漫步ASP.NET MVC的处理管线 ASP.NET MVC从诞生到现在已经好几个年头了,这个框架提供一种全新的开发模式,更符合web开发本质.你可以很好的使用以及个性化和扩展这个框架,但这需要你 ...
- MVC学习笔记---MVC生命周期
Asp.net应用程序管道处理用户请求时特别强调"时机",对Asp.net生命周期的了解多少直接影响我们写页面和控件的效率.因此在2007年和2008年我在这个话题上各写了一篇文章 ...
- MVC学习笔记---MVC生命周期及管道
ASP.NET和ASP.NET MVC的HttpApplication请求处理管道有共同的部分和不同之处,本系列将体验ASP.NET MVC请求处理管道生命周期的19个关键环节. ①以IIS6.0为例 ...
- MVC学习笔记---MVC导出excel(数据量大,非常耗时的,异步导出)
要在ASP.NET MVC站点上做excel导出功能,但是要导出的excel文件比较大,有几十M,所以导出比较费时,为了不影响对界面的其它操作,我就采用异步的方式,后台开辟一个线程将excel导出到指 ...
- 学习笔记48_Memcache跟用户登录模块结合
public interface ICacheWriter { void AddCache(string key,object value, DateTime expDate); void Add ...
- MVC学习笔记---MVC框架执行顺序
一.把路由添加到路由表, 二.注册ControllerBuilder(老板)和默认工厂(DefaultControllerFactory) 2.1默认工厂获取可以创建的Controller. 三.由于 ...
随机推荐
- 9.ORM数据访问
1.Spring对ORM的支持 ORM : 对象关系映射(Object Relational Mapping)是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术基于ORM的数据持久层框架有: ...
- shell脚本:Ctrl+C终止的是哪个进程
aa.sh中的内容如下图: 运行sh aa.sh, 显示aa.txt后面几行, 此时开启了两个进程:一个sh运行,一个tail -f运行 按Ctrl+C 会终止此sh进程, 父进程死了,里面的tail ...
- Java字符串拆分和字符串连接
Java字符串拆分/连接 public class LierString{ //------------------------------------------------------------ ...
- 经典网络LeNet5看卷积神经网络各层的维度变化
本文介绍以下几个CNN经典模型:Lenet(1986年).Alexnet(2012年).GoogleNet(2014年).VGG(2014年).Deep Residual Learning(2015年 ...
- 在vue2.x中安装sass并配置
在vue中安装sass先检查系统中有没有安装sass,在命令行中输入 sass -v 表示sass在电脑中已有,否者可以参考我这篇博客安装Sass遇到的坑 一.先安装sass cmd打开命令行,到项目 ...
- 转 oracle cursor 游标
转自:http://blog.csdn.net/liyong199012/article/details/8948952 游标的概念: 游标是SQL的一个内存工作区,由系统或用户以变量的形式定 ...
- “随机数”函数的 ES6 实现
生成一个指定长度的数字数组 const getNumArray = len => [...new Array(len).keys()]; const getNumArray = len => ...
- appium连接夜神模拟器方法总结
使用appium连接模拟器前提条件:appium环境已经搭建完毕,搭建步骤请参考我的博客:appium手机自动化环境搭建 1.下载并安装夜神模拟器:https://www.yeshen.com/ 2. ...
- Cookie和Session入门(一)
目录一)背景介绍二)Cookie机制三)Session机制四)两者比较五)参考资料链接一)背景介绍Cookie与Session是常用的会话跟踪技术.1.Cookie通过在客户端记录信息确定用户身份,S ...
- Android官方架构组件介绍之ViewModel(三)
ViewModel 像Activity,Fragment这类应用组件都有自己的生命周期并且是被Android的Framework所管理的.Framework可能会根据用户的一些操作和设备的状态对Act ...