asp.net mvc4 过滤器的简单应用:登录验证

直接上代码,不要说话。

ASP.NET MVC4过滤器的简单应用:验证登录

1    [AcceptVerbs(HttpVerbs.Post)]
2         public ActionResult login(FormCollection form)
3         {
4             Session["login"] = "True";
5             return Redirect("/Home/Index");
6 
7         }
View Code

 

1         [IsLogin]
2         public ActionResult Index() 
3         {
4             return View();
5         }
View Code

 

 1   //自定义过滤器
 2     public class IsLogin : ActionFilterAttribute
 3     {  
 4         //当方法执行时
 5         public override void OnActionExecuting(ActionExecutingContext filterContext)
 6         {
 7             //base.OnActionExecuting(filterContext);
 8             try
 9             {  var sess=filterContext.RequestContext.HttpContext.Session["login"];
10                 if (sess==null  ||sess.ToString()!="True")
11                     filterContext.Result = new RedirectResult("/Home/login");
12             }
13             catch
14             {
15                 filterContext.Result = new RedirectResult("/Shared/Error");
16             }
17         }
18 
19         //当方法执行完毕
20         public override void OnActionExecuted(ActionExecutedContext filterContext)
21         {
22             base.OnActionExecuted(filterContext);
23         }
24     }
View Code

 

 

 

 

 

 

 

 

posted @ 2013-06-23 23:13  Michael_Zeng  阅读(2708)  评论(0编辑  收藏  举报