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, "");
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用法并实现统一授权的更多相关文章

  1. Spring MVC学习笔记——完整的用户登录

    1.搭建环境的第一步是导包,把下面这些包都导入工程中 /media/common/工作/Ubuntu软件/SpringMVC_jar包整理/aop/media/common/工作/Ubuntu软件/S ...

  2. 前端MVC学习笔记(二)——AngularJS验证、过滤器、指令

    一.验证 angularJS中提供了许多的验证指令,可以轻松的实现验证,只需要在表单元素上添加相应的ng属性,常见的如下所示: <input Type="text" ng-m ...

  3. ASP.NET MVC学习笔记(二)登陆验证

    书上的验证时在配置文件中直接声明用户名和密码,想改成从数据验证账号和密码,搞了一下午都没高出来,不断的调试,发现 var table = userInfo.Tables.FirstOrDefault( ...

  4. MVC学习笔记---MVC的处理管线

    漫步ASP.NET MVC的处理管线   ASP.NET MVC从诞生到现在已经好几个年头了,这个框架提供一种全新的开发模式,更符合web开发本质.你可以很好的使用以及个性化和扩展这个框架,但这需要你 ...

  5. MVC学习笔记---MVC生命周期

    Asp.net应用程序管道处理用户请求时特别强调"时机",对Asp.net生命周期的了解多少直接影响我们写页面和控件的效率.因此在2007年和2008年我在这个话题上各写了一篇文章 ...

  6. MVC学习笔记---MVC生命周期及管道

    ASP.NET和ASP.NET MVC的HttpApplication请求处理管道有共同的部分和不同之处,本系列将体验ASP.NET MVC请求处理管道生命周期的19个关键环节. ①以IIS6.0为例 ...

  7. MVC学习笔记---MVC导出excel(数据量大,非常耗时的,异步导出)

    要在ASP.NET MVC站点上做excel导出功能,但是要导出的excel文件比较大,有几十M,所以导出比较费时,为了不影响对界面的其它操作,我就采用异步的方式,后台开辟一个线程将excel导出到指 ...

  8. 学习笔记48_Memcache跟用户登录模块结合

    public interface ICacheWriter {  void AddCache(string key,object value, DateTime expDate);  void Add ...

  9. MVC学习笔记---MVC框架执行顺序

    一.把路由添加到路由表, 二.注册ControllerBuilder(老板)和默认工厂(DefaultControllerFactory) 2.1默认工厂获取可以创建的Controller. 三.由于 ...

随机推荐

  1. mysql 备份时间 %date~0,4%和 %time~0,2%等用法详解

    比如在windowscmd命令行窗口执行date命令后这个环境变量的值为 当前日期:2014-09-01 星期六 或2014/09/01 周六 那么如下的各个操作的意义如下:%date:~0,4% 表 ...

  2. OJ 26217 :Work Scheduling(贪心+优先队列)

    约翰有太多的工作要做.为了让农场高效运转,他必须靠他的工作赚钱,每项工作花一个单位时间. 他的工作日从0时刻开始,有10^8个单位时间.在任一时刻,他都可以选择编号1~N的N(1 <= N &l ...

  3. ssh连接异常

    在平时工作中,有时候需要SSH登陆到别的Linux主机上去,但有时候SSH登陆会被禁止,并弹出如下类似提示: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ...

  4. Rabbitmq相关学习网址

    1.安装文档: http://www.cnblogs.com/shuzhenyu/p/9823324.html 2.RabbitMq的整理 exchange.route.queue关系 https:/ ...

  5. Go语言基础之6--值类型和引用类型

    一. 引用类型 引用类型理解为(C语言):指针 Golang中只有三种引用类型:slice(切片).map(字典).channel(管道): 实例1-1 package main import &qu ...

  6. VScode中Go的相关插件的安装

    一.安装Go插件失败 使用VScode时,当我们安装完go语言扩展时,新建一个go的源码文件,进行保存时,会提示我们需要安装一些go的扩展插件,可别小看这些插件,这些插件都是非常有用的,比如说自动补全 ...

  7. thinkPHP Model的操作

    1.建立一个表 create table Demo( -> id int, ), -> age int, ) -> ); 2.新增数据 2.1面向过程的风格 $d = $a-> ...

  8. android 闹钟设置问题

    Android开发中,alarmManager在5.0以上系统,启动时间设置无效的问题 做一个app,需要后台保持发送心跳包.由于锁屏后CPU休眠,导致心跳包线程被挂起,所以尝试使用alarmMana ...

  9. poi 详细demo

    import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IO ...

  10. (转)mkpasswd 的使用

    原文:http://blog.csdn.net/u010339879/article/details/69788032 这个命令是随机生成 密码的一个工具, 如果没有这个命令,请安装相应的包. yum ...