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. 三.由于 ...
随机推荐
- P3802 小魔女帕琪
传送门 考虑前面7个魔法 如果前面七个魔法各不相同,那么就能完成一次帕琪七重奏 设 A=a1*a2*...*a7,S=a1+a2+...+a7,B=S*(S-1)*...*(S-6) 对于不同的施法顺 ...
- 75th LeetCode Weekly Contest All Paths From Source to Target
Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and re ...
- django 请求体和请求体相关知识
请求头ContentType ContentType指的是请求体的编码类型,常见的类型共有3种: django 如果发送post请求,或者表单提交数据.如果不设置enctype属性. 就会以appli ...
- PreparedStatement是如何防止SQL注入的?
为什么在Java中PreparedStatement能够有效防止SQL注入?这可能是每个Java程序员思考过的问题. 首先我们来看下直观的现象(注:需要提前打开mysql的SQL文日志) 1. 不使用 ...
- docker基本命令日志
docker run - Run a command in a new container 启动一个新的容器,一般在docker pull之后首次运行此image -i 保持stdout打开 -t 打 ...
- 正则表达式获取多个img src的值
/** * 得到网页中图片的地址 */public static Set<String> getImgStr(String htmlStr) { Set<String> pic ...
- 【3dsMax安装失败,如何卸载、安装3dMax 2018?】
AUTODESK系列软件着实令人头疼,安装失败之后不能完全卸载!!!(比如maya,cad,3dsmax等).有时手动删除注册表重装之后还是会出现各种问题,每个版本的C++Runtime和.NET f ...
- [转]jQuery插件写法总结以及面向对象方式写法
本文转自:http://www.xuanfengge.com/jquery-plug-in-written-summary-and-summary-of-writing-object-oriented ...
- MATLAB循环和函数定义,调用
格式不要括号,最后有end for 循环变量 = 表达式1:表 2:表 3 表1:初值 表2:步长 表3:终值 求圆周率:π/4=1 - 1/3 + 1/5 -1/7+...+(-1 ...
- DEDE [field:global name=autoindex/] 按序列号递增
在用织梦仿站的时候,有些class样式是btn1.btn2这样的样式循环的,这个时候1.2可以用[field:global name=autoindex/ ] 循环得到,[field:global n ...