MVC4方法行为过滤器例子(用户登录)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MVC4方法行为过滤器例子(用户登录)相关的知识,希望对你有一定的参考价值。
在Model文件夹下添加一个类MyActionFilterAttribute继承于ActionFilterAttribute:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcValidateDemo.Models { //AllowMultiple = true:允许多个标签同时都起作用 [AttributeUsage(AttributeTargets.All,AllowMultiple = true)] public class MyActionFilterAttribute : ActionFilterAttribute { public string Name { get; set; } //Action执行之前先执行此方法 public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); //HttpContext.Current.Response.Write("<br />执行OnActionExecuting方法:" + Name); //例子:获取session值,找不到则跳转页面 string session = HttpContext.Current.Session["user"] == null ? string.Empty : HttpContext.Current.Session["user"].ToString(); if (string.IsNullOrEmpty(session)) { HttpContext.Current.Response.Redirect("/Home/About"); return; } } //Action执行之后 public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); HttpContext.Current.Response.Write("<br />执行OnActionExecuted方法:" + Name); } //ActionResult执行之前先执行此方法,返回结果前执行方法 public override void OnResultExecuting(ResultExecutingContext filterContext) { base.OnResultExecuting(filterContext); HttpContext.Current.Response.Write("<br />执行OnResultExecuting方法:" + Name); } //返回结果后执行方法 public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); HttpContext.Current.Response.Write("<br />执行OnResultExecuted方法:" + Name); } } }
添加一个控制器:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcValidateDemo.Models; namespace MvcValidateDemo.Controllers { //[MyActionFilter(Name = "HomeController")] //过滤控制器 public class HomeController : Controller { //[MyActionFilter(Name = "Index Action")] //过滤Action [MyActionFilter] public ActionResult Index() { //Response.Write("<p>Action执行了</p>"); //return Content("<br />ok:视图被渲染<br />"); return View(); } public ActionResult Login() { Session["user"] = "user"; return Content("登录成功"); } public ActionResult About() { return View(); } } }
当执行Home下Index尝试登录时,会先去执行过滤器的OnActionExecuting方法,过滤器会先判断是否有Session值,如果没找到则跳转页面到/Home/About,当先登录执行/Home/Login时,会将Session值放到服务器中,再次执行/Home/Index则不会跳转
以上是关于MVC4方法行为过滤器例子(用户登录)的主要内容,如果未能解决你的问题,请参考以下文章
在c#的mvc4中,用httpcontext.user还是session保存用户登录信息?