ASP.NET MVC使用过滤器进行权限控制

1.新建MVC项目

2.找到Models文件夹,新建 LoginCheckFilterAttribute 类

  public class LoginCheckFilterAttribute : ActionFilterAttribute
{
public bool IsCheck { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext); if (IsCheck)
{
//校验用户是否已经登录
if (filterContext.HttpContext.Session["loginUser"] == null)
{
filterContext.HttpContext.Response.Redirect("/UserLogin/Index");
}
} filterContext.HttpContext.Response.Write("开始时间:" + DateTime.Now.ToString() + "<br/>");
} public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var controllerName = filterContext.RouteData.Values["controller"].ToString();
var actionName = filterContext.RouteData.Values["action"].ToString();
filterContext.HttpContext.Response.Write("结束时间:" + DateTime.Now.ToString() + "<br/>");
filterContext.HttpContext.Response.Write("controller:" + controllerName + ",action:" + actionName);
}
}

LoginCheckFilterAttribute

3.找到App_Start下的 FilterConfig.cs 添加以下代码

     public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute()); filters.Add(new LoginCheckFilterAttribute() { IsCheck = true });
}
}

FilterConfig

4.使用方式

 [LoginCheckFilter(IsCheck = false)]
public class UserLoginController : BaseController
{
public UserLoginController()
{
this.IsCheckLogin = false;
}
//
// GET: /UserLogin/ [LoginCheckFilter(IsCheck = true)]
public ActionResult Index()
{
return View();
}
}

UserLoginController

End

1.扩展基类进行权限控制

  public class BaseController : Controller
{
//在当前控制器所有方法之前执行,都先执行此代码
public bool IsCheckLogin = true; protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext); if (IsCheckLogin)
{
//校验用户是否已经登录
if (filterContext.HttpContext.Session["loginUser"] == null)
{
filterContext.HttpContext.Response.Redirect("/UserLogin/Index");
}
}
}
}

BaseController

2.调用方式

  public class UserLoginController : BaseController
{
public UserLoginController()
{
this.IsCheckLogin = false;
}
}

UserLoginController

上一篇:Android(Intent 学习)


下一篇:C[a,b]向量空间中的函数的线性相关性